欢迎关注微信公众号 C#编程大全 这里有更多入门级实例帮你快速成长

在C#交流群里,看到很多小伙伴在excel数据导入导出到C#界面上存在疑惑,所以今天专门做了这个主题,希望大家有所收获!

环境:win10+vs2017

界面:主要以演示为主,所以没有做优化,然后主界面上添加两个按钮,分别命名为ExportExcel和ImportExcel,添加两个dataGridView,分别是dataGridView1和dataGridView2

然后在窗体加载程序中给dataGridView1写入三行数据,代码如下:

DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Rows.Add("小王","15");
            dt.Rows.Add("老李","42");
            dt.Rows.Add("老张","25");
            dataGridView1.DataSource = dt;

软件运行后,点击ExportExcel,则将datagridview1的数据保存到excel中,点击ImportExcel,选择excel后读取数据到datagridview2.

注意:如果报System.InvalidOperationException:“未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。”请检查office是否正确安装

具体步骤:

step1:引用dll,在nuget上安装Microsoft.Office.Interop.Excel

step2:code

主要由三个方法:

  1. public void ExportExcel() 实现数据导出到excel

  2. public DataSet ImportExcel(int t = 1)实现读取excel数据

  3. public void ExportCSV() 数据导出到csv

    完整代码如下:

  4. using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms; using System.IO;
    using System.Data.SqlClient;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Reflection;
    using System.Xml;
    using System.Data.OleDb; namespace excelReadWriter
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    } #region /* 数据导出到excel */
    public void ExportExcel()
    {
    try
    {
    this.Cursor = Cursors.WaitCursor; if (!Directory.Exists(@"C:\BMDT"))
    Directory.CreateDirectory(@"C:\BMDT"); string fileName = "";
    string saveFileName = "";
    SaveFileDialog saveDialog = new SaveFileDialog();
    saveDialog.DefaultExt = "xlsx";
    saveDialog.InitialDirectory = @"C:\BMDT";
    saveDialog.Filter = "Excel文件|*.xlsx";
    // saveDialog.FileName = fileName;
    saveDialog.FileName = "BMDT_Data_" + DateTime.Now.ToLongDateString().ToString();
    saveDialog.ShowDialog();
    saveFileName = saveDialog.FileName; if (saveFileName.IndexOf(":") < 0)
    {
    this.Cursor = Cursors.Default;
    return; //被点了取消
    }
    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    if (xlApp == null)
    {
    MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
    return;
    }
    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
    Microsoft.Office.Interop.Excel.Range range = worksheet.Range[worksheet.Cells[4, 1], worksheet.Cells[8, 1]]; //写入标题
    for (int i = 0; i < dataGridView1.ColumnCount; i++)
    { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
    //写入数值
    for (int r = 0; r < dataGridView1.Rows.Count; r++)
    {
    for (int i = 0; i < dataGridView1.ColumnCount; i++)
    {
    worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value; if (this.dataGridView1.Rows[r].Cells[i].Style.BackColor == Color.Red)
    { range = worksheet.Range[worksheet.Cells[r + 2, i + 1], worksheet.Cells[r + 2, i + 1]];
    range.Interior.ColorIndex = 10; } }
    System.Windows.Forms.Application.DoEvents();
    }
    worksheet.Columns.EntireColumn.AutoFit();//列宽自适应 MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK);
    if (saveFileName != "")
    {
    try
    {
    workbook.Saved = true;
    workbook.SaveCopyAs(saveFileName); //fileSaved = true; }
    catch (Exception ex)
    {//fileSaved = false;
    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
    }
    }
    xlApp.Quit();
    GC.Collect();//强行销毁 this.Cursor = Cursors.Default;
    }
    catch(Exception e)
    {
    this.Cursor = Cursors.Default;
    MessageBox.Show(e.ToString()); } } #endregion
    #region /* ImportExcel(int t) */ public DataSet ImportExcel(int t = 1)
    {
    //打开文件
    string sql_select = string.Empty; OpenFileDialog file = new OpenFileDialog();
    file.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls|(*.csv)|*.csv";
    file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
    file.Multiselect = false;
    if (file.ShowDialog() == DialogResult.Cancel)
    return null;
    //判断文件后缀
    var path = file.FileName;
    string fileSuffix = System.IO.Path.GetExtension(path);
    if (string.IsNullOrEmpty(fileSuffix))
    return null;
    using (DataSet ds = new DataSet())
    {
    //判断Excel文件是2003版本还是2007版本
    string connString = "";
    if (fileSuffix == ".xls")
    connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
    else
    connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
    //读取文件 if (t == 1)
    sql_select = " SELECT ID,CREATETIME,REASONCODE1,PROCESSID FROM [Sheet1$] ";
    else if (t == 2)
    sql_select = " SELECT PANELID,EVENTTIME,DESCRIPTION,PROCESSID FROM [Grid$] ";
    else if (t == 3)
    sql_select = " SELECT Operation,Lot_ID,EQP_ID,Event_Time FROM [报表1$] "; using (OleDbConnection conn = new OleDbConnection(connString))
    using (OleDbDataAdapter cmd = new OleDbDataAdapter(sql_select, conn))
    {
    conn.Open();
    cmd.Fill(ds);
    }
    if (ds == null || ds.Tables.Count <= 0) return null;
    return ds;
    }
    }
    #endregion private void button1_Click(object sender, EventArgs e)
    {
    ExportExcel();
    } private void Form1_Load(object sender, EventArgs e)
    {
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Age");
    dt.Rows.Add("小王","15");
    dt.Rows.Add("老李","42");
    dt.Rows.Add("老张","25");
    dataGridView1.DataSource = dt;
    } private void button2_Click(object sender, EventArgs e)
    {
    DataSet ds = new DataSet();
    ds = ImportExcel();
    dataGridView2.DataSource = ds.Tables[0]; // ExportCSV();
    } #region /* 数据导出到CSV */
    public void ExportCSV()
    {
    if (dataGridView1.Rows.Count == 0)
    {
    MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
    }
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
    saveFileDialog.FilterIndex = 0;
    saveFileDialog.RestoreDirectory = true;
    saveFileDialog.CreatePrompt = true;
    saveFileDialog.FileName = null;
    saveFileDialog.Title = "保存";
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
    Stream stream = saveFileDialog.OpenFile();
    StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
    string strLine = "";
    try
    {
    for (int i = 0; i < dataGridView1.ColumnCount; i++)
    {
    if (i > 0)
    strLine += ","; strLine += dataGridView1.Columns[i].HeaderText; } strLine.Remove(strLine.Length - 1); sw.WriteLine(strLine); strLine = ""; //表的内容 for (int j = 0; j < dataGridView1.Rows.Count; j++)
    { strLine = ""; int colCount = dataGridView1.Columns.Count; for (int k = 0; k < colCount; k++)
    { if (k > 0 && k < colCount) strLine += ","; if (dataGridView1.Rows[j].Cells[k].Value == null) strLine += ""; else
    { string cell = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim(); //防止里面含有特殊符号 cell = cell.Replace("\"", "\"\""); cell = "\"" + cell + "\""; strLine += cell; } } sw.WriteLine(strLine); } sw.Close(); stream.Close(); MessageBox.Show("数据被导出到:" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex)
    {
    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information); }
    }
    }
    #endregion
    }
    }

      运行效果:

    小编微信号z438679770

最新文章

  1. Java Thread 的 sleep() 和 wait() 的区别
  2. openstack问题汇总
  3. C开源hash项目uthash
  4. ActiveMQ源码架构解析第一节(转)
  5. [iOS]C语言技术视频-02-程序分支结构(if...else)
  6. Python内置数据类型总结
  7. Linq To EF
  8. MySQL 的几种进入方式
  9. &quot;i=i++&quot;在java等高级语言的解释
  10. 2018.4.25 github创建新项目
  11. Beta冲刺! Day2 - 砍柴
  12. 2.0 vue内置指令与自定义指令
  13. perventDefault, stopPropagation, stopImmediatePropagation 三者的区别
  14. ref:linux查看用户登录时间以及命令历史
  15. llvm code call graph
  16. poj3728The merchant 【倍增】【LCA】
  17. 记python3 UnicodeEncodeError: &#39;latin-1&#39; codec... 报错
  18. springboot之cas客户端
  19. mysql 5.7 json 字段类型查找、修改
  20. 洛谷——P1109 学生分组

热门文章

  1. 转载:Java的三种取整办法
  2. vue3剖析:响应式原理——effect
  3. Java查找指定文件中指定字符的个数
  4. selenium做UI自动化时,模拟鼠标各种操作的ActionChains的用法
  5. [LeetCode]621. 任务调度器(贪心)
  6. [Codeforces1174B]Ehab Is an Odd Person
  7. MySQL&lt;=&gt;是什么鬼
  8. Python3使用钉钉机器人推送消息(签名方式)
  9. Orchard Core创建CMS/Blog站点
  10. Oracle学习(九)存过、游标、RECORD整合