在实际项目中,不可避免的会操作excel表格。一直以来都是读取excel表格,可今天为了写入excel表格,可是煞费苦心,终于完成,记录下来以便后续使用。
1、读取excel表格的数据
读取excel数据,然后导入到数据库中,根据常识,只要是能得到一个dataset,那所有的问题便迎刃而解了。下面将读取excel数据得到dataset:
public DataSet ExecleDs(string filenameurl) { string strConn = "Provider=Microsoft.ACE.OleDb.12.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 12.0; HDR=YES; IMEX=1'"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataSet ds = new DataSet(); string strSql = string.Format("SELECT * FROM [{0}$]", "Sheet1"); OleDbDataAdapter odda = new OleDbDataAdapter(strSql, conn); odda.Fill(ds, "hou"); return ds; }
2、写入数据到excel表格
首先加入两个引用:
using System.Reflection; using Microsoft.Office.Interop.Excel;
1)初始化:
object missing = Missing .Value ; Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();//实例化excel对象 Microsoft.Office.Interop.Excel.Workbook rsBook = excel.Workbooks.Open(fullFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);//打开目标文件 Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)rsBook.Sheets.get_Item(1);//设置第一个工作薄 excelSheet.Activate();//激活当前工作簿
2)写入数据:
for (int i = 1; i < 5; i++) { excelSheet.Cells[i, 1] = i; excelSheet.Cells[i, 2] = i + 5; excelSheet.Cells[i, 3] = i + 10; }
注:excel表格的第一行、第一列都是以1开始的。
3)保存excel文件、设置Application的属性,并回收资源
rsBook.Save(); excel.DisplayAlerts = false; excel.Visible = true; excelSheet = null; rsBook = null; excel = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers();