C#導(dǎo)入和導(dǎo)出CSV文件
更新時間:2022年05月26日 09:14:55 作者:springsnow
這篇文章介紹了C#導(dǎo)入和導(dǎo)出CSV文件的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
一、手工導(dǎo)出導(dǎo)出
1、winform
void DataGridViewToExcel(DataGridView dataGridView1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "保存為Excel文件";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream stream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
string columnTitle = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
columnTitle += "\t";//或者為逗號
}
columnTitle += dataGridView1.Columns[i].HeaderText;//寫入列標(biāo)題
}
sw.WriteLine(columnTitle);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string columnValue = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
columnValue += "\t";
}
columnValue += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(columnValue);
}
sw.Close();
stream.Close();
}
finally
{
sw.Close();
stream.Close();
}
}
}2、Web導(dǎo)出
不用存磁盤文件<iframe>導(dǎo)出。
string exportFileName = "Export" + DateTime.Now.ToString("yyyyMMddHHmmss");
System.Web.HttpContext context = System.Web.HttpContext.Current;
StringBuilder sb = new StringBuilder();
sb.Append("FirstName,LastName,PhoneNo.,State,TimeZone,ZipCode\n");
for (int i = 0; i < result.PhoneList.Count; i++)
{
sb.Append(result.PhoneList[i].FirstName + "," + result.PhoneList[i].LastName + "," + result.PhoneList[i].ZipCode + "\n");
}
StringWriter sw = new StringWriter(sb);//一定要StringWriter/StreamWriter才能直接導(dǎo)出
sw.Close();
context.Response.ClearHeaders();
context.Response.Clear();
context.Response.Charset = "UTF-8";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.HeaderEncoding = System.Text.Encoding.UTF8;
context.Response.ContentType = "text/csv";
context.Response.BinaryWrite(new byte[] { 0xEF, 0xBB, 0xBF });//防止中文亂碼
context.Response.Write(sw);
context.Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode("1.csv", System.Text.Encoding.UTF8).Replace("+", "%20"));
sw.Close();
context.Response.Flush();
context.Response.End();二、利用LumenWorks.Framework.IO.Csv讀取CSV文件
需要引用LumenWorks.Framework.IO.dll,讀取的時候編碼格式要選對,否則會亂碼,表頭自己設(shè)置
- phatcher/CsvReader: Extended version of Sebastian Lorien's fast CSV Reader (github.com)
- NuGet Gallery | LumenWorksCsvReader 4.0.0
static DataTable GetData(Stream stream)
{
using (stream)
{
using (StreamReader input = new StreamReader(stream, Encoding.GetEncoding("shift_jis")))
{
using (CsvReader csv = new CsvReader(input, false))
{
DataTable dt = new DataTable();
int columnCount = csv.FieldCount;
for (int i = 0; i < columnCount; i++)
{
dt.Columns.Add("col" + i.ToString());
}
while (csv.ReadNextRecord())
{
DataRow dr = dt.NewRow();
for (int i = 0; i < columnCount; i++)
{
if (!string.IsNullOrWhiteSpace(csv[i]))
{
dr[i] = csv[i];
}
}
dt.Rows.Add(dr);
}
return dt;
}
}
}
}基本使用場景
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv =
new CsvReader(new StreamReader("data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
for (int i = 0; i < fieldCount; i++)
Console.Write(string.Format("{0} = {1};",
headers[i], csv[i]));
Console.WriteLine();
}
}
}復(fù)雜的數(shù)據(jù)綁定方案(Windows窗體)
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CachedCsvReader csv = new
CachedCsvReader(new StreamReader("data.csv"), true))
{
// Field headers will automatically be used as column names
myDataGrid.DataSource = csv;
}
}到此這篇關(guān)于C#導(dǎo)入和導(dǎo)出CSV文件的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
WPF實現(xiàn)XAML轉(zhuǎn)圖片的示例詳解
這篇文章主要為大家詳細介紹了如何利用WPF實現(xiàn)XAML轉(zhuǎn)圖片,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2022-11-11
C#實現(xiàn)將Email地址轉(zhuǎn)成圖片顯示的方法
這篇文章主要介紹了C#實現(xiàn)將Email地址轉(zhuǎn)成圖片顯示的方法,涉及C#操作圖片的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C#實現(xiàn)文件與二進制互轉(zhuǎn)并存入數(shù)據(jù)庫
這篇文章主要介紹了C#實現(xiàn)文件與二進制互轉(zhuǎn)并存入數(shù)據(jù)庫,本文直接給出代碼實例,代碼中包含詳細注釋,需要的朋友可以參考下2015-06-06
C# 操作PostgreSQL 數(shù)據(jù)庫的示例代碼
本篇文章主要介紹了C# 操作PostgreSQL 數(shù)據(jù)庫的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11

