- 在使用用本文的方法前,需要先安装Office 的Excel程序,然后,引用 Excel 的对象包装:
- using Microsoft.Office.Interop.Excel;
不同的Office版本可能引用的名称不同。
使用下面的代码,完成数据写入操作:
- private void writeData(string excelFileName,DataSet dsResult,)
- {
- _Application xlApp = null;
- _Workbook xlWorkbook = null;
- _Worksheet xlWorksheet = null;
- System.Reflection.Missing missing = System.Reflection.Missing.Value;
- string saveAsPath = "";
- try
- {
- xlApp = new ApplicationClass();
- xlApp.Visible =true ;
- xlWorkbook=xlApp.Workbooks.Open(excelFileName, missing, missing, missing, missing, missing, missing, missing,
- missing, missing, missing, missing, missing, missing, missing);
- xlWorksheet = xlWorkbook.Worksheets[1] as _Worksheet;
- //xlWorksheet.Name = "NewWorksheet";
- //xlWorksheet.Cells[1, "A"] = "Topic: ";
- //xlWorksheet.Cells[1, "B"] = ".Net Interop Excel Demo";
- for (int x = 4; x < 92; x++)
- {
- object rang = xlWorksheet.Cells[x, "D"];
- if (rang != null)
- {
- object objText = ((Range)rang).Value2;
- string strCellText = objText==null?"":objText.ToString();
- if (strCellText == "")
- {
- rang = xlWorksheet.Cells[x, "C"];
- strCellText = "";
- if (rang != null)
- {
- objText = ((Range)rang).Value2;
- strCellText = objText == null ? "" : objText.ToString();
- }
- }
- //xlWorksheet.Cells[x, "E"] = strCellText;
- DataRow[] rows = dsResult.Tables[0].Select("Name='" + strCellText + "'");
- if (rows.Length > 0)
- {
- //防止有空值
- if(rows[0]["Count"]!=DBNull.Value )
- xlWorksheet.Cells[x, "H"] = rows[0]["Count"].ToString();
- }
- }
- }
- xlWorkbook.Save();
- //saveAsPath = System.Windows.Forms.Application.StartupPath + "//" + xlWorkbook.Name;
- //xlWorkbook.SaveAs(saveAsPath, missing, missing, missing, missing,
- // missing, XlSaveAsAccessMode.xlShared, missing, missing, missing,
- // missing, missing);
- //xlApp.Quit();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message);
- }
- finally
- {
- //System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
- //xlApp = null;
- //GC.Collect();
- }
- }
本例没有直接关闭文件,如果你要另存为一个文件,把注释取消即可。
注意获取单元格的方法:
- rang = xlWorksheet.Cells[x, "C"];
- strCellText = "";
- if (rang != null)
- {
- objText = ((Range)rang).Value2;
- strCellText = objText == null ? "" : objText.ToString();
- }