C# excel文件导入导出

2020-08-19 14:24:16 浏览数 (1)

在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. 保存选项对话框 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; //被点了取消 } 完整代码如下:
代码语言:javascript复制
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
    }
}

运行效果:

如果你想把数据导入csv文件,则可以用以下方法:

代码语言:javascript复制
 #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

0 人点赞