您的位置:首页 > 编程语言 > C#

C#读取EXCEL 文件同时向文件中写入数据和Excel的Range对象

2017-04-21 22:15 961 查看
今天用C#写了一个小软件就是读取一个EXCEL文件中的数据进行计算,然后将数据再写进EXCEL 文件中;在网上查了一下相关的帖子,这里我也总结一下:

首先C#读取EXCEL有三种经典的方法:分别是:

    1、采用OleDB读取EXCEL文件

    2、引用的com组件:Microsoft.Office.Interop.Excel.dll   读取EXCEL文件

    3、将EXCEL文件转化成CSV(逗号分隔)的文件,用文件流读取(等价就是读取一个txt文本文件)。

在这里我采用的是用第二种方法即用Microsoft.Office.Interop.Excel.dll   读取EXCEL文件。

首先是引用Microsoft.Office.Interop.Excel.dll
文件,这个文件可以直接通过百度直接下载,然后添加引用即可。

然后在命名空间上面输入: using System.Reflection;

                                            using Excel = Microsoft.Office.Interop.Excel;

这里附上我写的代码:

object missing = System.Reflection.Missing.Value;

            //创建Excel对象

            Excel.Application excelApp = new Excel.Application();

            Excel.Workbook wb = excelApp.Workbooks.Open(filePath, missing, false, missing, missing, missing,

             missing, missing, missing, true, missing, missing, missing, missing, missing);

            //取得第一个工作薄

            Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);

 //取得总记录行数  

                int rowsint = ws.UsedRange.Cells.Rows.Count; //得到行数

                int columnsint = ws.UsedRange.Cells.Columns.Count;//得到列数

                Excel.Range rng1 = ws.Rows["1:3", Type.Missing]; //item

                object[,] arr = (object[,])rng1.Value2;

                double[] arrSO2 = new double[columnsint - 1];

                double[] arrNox = new double[columnsint - 1];

                double[] arrCO = new double[columnsint - 1];

                string str = "";

                for (int i = 0; i < columnsint - 1; i++)

                {

                    arrSO2[i] = Convert.ToDouble(arr[1, i + 2]);

                    arrNox[i] = Convert.ToDouble(arr[2, i + 2]);

                    arrCO[i] = Convert.ToDouble(arr[3, i + 2]);

                }

通过上面的代码就可以获取到EXCEL文件中数据;

然后是将数据写入到EXCEL文件中:

  ws.Cells[4, 7] = "SO2浓度标准偏差:";

                ws.Cells[4, 8] = standardSO2.ToString();

                ws.Cells[5, 7] = "NOX浓度标准偏差:";

                ws.Cells[5, 8] = stanardNOX.ToString();

下面代码也必须要有

               wb.Save();

                excelApp.Quit();

                wb = null;

                ws = null;

                excelApp = null;

 Process[] procs = Process.GetProcessesByName("excel");

                foreach (Process pro in procs)

                {

                    pro.Kill();//没有更好的方法,只有杀掉进程

                }

                GC.Collect();

上面的代码中在获取数据的时候有很多方法,这里我附上我在网上看到的一个链接,比较详细:

点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据 c# excel