C# excel操作

excel应用非常普遍,C#操作excel非常方便。本文介绍两种操作excel的方法。第一种是系统自带的库System.Data.OleDb;用此库操作exce需要对两种格式进行区分(.xls和.xlsx)。

1、定义连接字符串

            string fileName =@"....data.xlsx";
            string ex = Path.GetExtension(fileName);
            string connString=null;
            if (ex==".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";
            }
            else if (ex == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + fileName + ";" + ";Extended Properties="Excel 8.0;HDR=YES;IMEX=1"";
            }
            else
            {
                return;
            }

2、连接excel并读取数据(跟其他数据库读取无异)

            OleDbConnection conn = new OleDbConnection(connString);
            conn.Open();

            OleDbCommand oleDBCmd = conn.CreateCommand();
            oleDBCmd.CommandText = "select *from[Sheet1$]";
            OleDbDataAdapter apt =new OleDbDataAdapter(oleDBCmd);
            DataSet ds = new DataSet();
            apt.Fill(ds,"t1");
            DataTable dt = ds.Tables["t1"];
            for(int i=0;i<dt.Rows.Count;i++)
            {
                Console.Write(dt.Rows[i][0] + "  ");
                Console.Write(dt.Rows[i][1]+"  ");
                Console.Write(dt.Rows[i][2] + "  ");
                Console.WriteLine(dt.Rows[i][3]);
            }
            Console.ReadKey();

            oleDBCmd.Dispose();
            conn.Close();
           

此方法由于使用数据库语言,所以每次只能读取一个表格(sheet),要想读取多个表格,需要借助string.format多次读取excel文件。

下面介绍一种比较方便的方法,引用库Aspose.Cells.dll可以很方便的进行读取。它首先定义workbook(即excel文件)并与相关文件连接,然后通过workbook里面的worksheet获取excel文件中的表单,在通过cells获取相应的单元格数据。下面是具体步骤:

1、引用Aspose.Cells

using Aspose.Cells;

2、建立workbook,并连接excel

            string newCreateExcelFile = @"....
ew.xlsx";
            string fileName = @"....data.xlsx";
            Workbook excelWorkBook = new Workbook(fileName);

3、获取数据

            Console.WriteLine(excelWorkBook.Worksheets.Count);//excel中表单个数
            foreach (Worksheet sheet in excelWorkBook.Worksheets)
            {
              
                Console.WriteLine(sheet.Name+"  ");//excel中表单名字
            }

            // 获取某一表单中第二列数据
            Worksheet sheet1 = excelWorkBook.Worksheets[4];
            for(int i=0;i<sheet1.Cells.Rows.Count;i++)
            {
                Console.WriteLine(sheet1.Cells[i, 1].StringValue);
            }

4、新建excel,可以利用此库方便的建立excel文件

            //新建文件
            Workbook newCreated = new Workbook();
            newCreated.Worksheets.Clear();

            //添加表单
            newCreated.Worksheets.Add("01");
            Worksheet ws = newCreated.Worksheets["01"];
            //添加数据
            ws.Cells[0, 0].Value = "afdsfd";
            //保存文件
            newCreated.Save(newCreateExcelFile);
原文地址:https://www.cnblogs.com/llstart-new0201/p/6817230.html