欢迎来到代码驿站!

当前位置:首页 >

C#导入和导出CSV文件

时间:2023-03-01 15:10:48|栏目:|点击:

一、手工导出导出

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;//写入列标题
            }
            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导出

不用存磁盘文件<iframe>导出。

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才能直接导出
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,读取的时候编码格式要选对,否则会乱码,表头自己设置

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();
        }
    }
}

复杂的数据绑定方案(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;
    }
}

上一篇:springboot整合curator实现分布式锁过程

栏    目:

下一篇:android Retrofit2+okHttp3使用总结

本文标题:C#导入和导出CSV文件

本文地址:http://www.codeinn.net/misctech/226653.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有