前言: 前幾天一同事問我如何利用C#將數據導到Excel文件當中,當時比較忙沒有 顧得上去研究,今天特地研究了一下,基本搞定,下面就具體介紹如何將 DataView中的數據按照一定格式存到Excel文件當中。 正文: 一、首先要引用一個Excel的組件,我一開始是在Office XP下嘗試的,不 成功,后來把XP給干掉,裝2k,就成功了,所以這里分享的是Office 2k下 引用相關組件來實現功能的,在工程中引用COM標簽中的Microsoft Excel 9.0 Object Library,添加成功后,引用中會多出三個引用項: Excel、Office、VBIDE。
二、具體代碼。 using System; using System.Data; using Excel; using System.IO; namespace Test.ExcelCom { /// <summary> /// 將DataView中的數據導入Excel文件中 /// 作者:Rexsp /// 創建:2004-4-4 /// </summary> public class OutputExcel { #region 私有成員 /// <summary> /// 數據的DataView /// </summary> private DataView dv=null; /// <summary> /// 表格標題 /// </summary> private string title=null; /// <summary> /// 輸出文件路徑 /// </summary> private string outFilePath=null; /// <summary> /// 輸入文件名 /// </summary> private string inputFilePath=null; #endregion #region 公共屬性 /// <summary> /// 數據的DataView /// </summary> public DataView DV { set{dv=value;} } /// <summary> /// 表格標題 /// </summary> public string Title { set{title=value;} get{return title;} } /// <summary> /// 輸出文件路徑 /// </summary> public string OutFilePath { set{outFilePath=value;} get{return outFilePath;} } /// <summary> /// 輸入文件路徑 /// </summary> public string InputFilePath { set{inputFilePath=value;} get{return inputFilePath;} } #endregion #region 構造函數 public OutputExcel() { } public OutputExcel(DataView dv,string title) { // // TODO: 在此處添加構造函數邏輯 // } #endregion #region 公共方法 public void CreateExcel() { int rowIndex=4;//行起始坐標 int colIndex=1;//列起始坐標 ApplicationClass myApp=null; Workbook myBook=null; Worksheet mySheet=null; //如果文件不存在,則將模板文件拷貝一份作為輸出文件 //這里如果通過File.Create來創建文件是不行的,因為xls //的空文件也有固定的格式,跟文本不一樣的,也許有其它 //通過程序直接生成excel的方法,大家可以嘗試嘗試的 if(!File.Exists(outFilePath)) { File.Copy(inputFilePath,outFilePath,true); } myApp= new ApplicationClass(); myApp.Visible=false; object oMissiong=System.Reflection.Missing.Value; myApp.Workbooks.Open(outFilePath,oMissiong,oMissiong,oMissiong,oMissiong, oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong); myBook=myApp.Workbooks[1]; mySheet=(Worksheet)myBook.ActiveSheet;
// //取得標題 // foreach(DataColumn col in dv.Table.Columns) { colIndex++; mySheet.Cells[4,colIndex] = col.ColumnName; mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter; //設置標題格式為居中對齊 } // //取得表格中的數據 // foreach(DataRowView row in dv) { rowIndex ++; colIndex = 1; foreach(DataColumn col in dv.Table.Columns) { colIndex ++; if(col.DataType == System.Type.GetType("System.DateTime")) { mySheet.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設置日期型的字段格式為居中對齊 } else if(col.DataType == System.Type.GetType("System.String")) { mySheet.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString(); mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設置字符型的字段格式為居中對齊 } else { mySheet.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString(); } } } // //加載一個合計行 // int rowSum = rowIndex + 1; int colSum = 2; mySheet.Cells[rowSum,2] = "合計"; mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter; // //設置選中的部分的顏色 // mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Select(); mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//設置為淺黃色,共計有56種 // //取得整個報表的標題 // mySheet.Cells[2,2] = title; // //設置整個報表的標題格式 // mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Bold = true; mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Size = 22; // //設置報表表格為最適應寬度 // mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Select(); mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Columns.AutoFit(); // //設置整個報表的標題為跨列居中 // mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).Select(); mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection; // //繪制邊框 // mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Borders.LineStyle = 1; mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//設置左邊線加粗 mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//設置上邊線加粗 mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//設置右邊線加粗 mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//設置下邊線加粗 myBook.Save();; myBook.Close( true,outFilePath,true); System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp); GC.Collect();
} #endregion }
} 一點說明:操作Excel的時候,可能會發生Excel進程被鎖定,無法退 出,解決方法是在保存完并關閉myBook(工作簿)后,別關閉Excel進 程(//myApp.Quit();)。這樣的結果是服務器上始終有一個Excel的 進程。可能會出現asp_net用戶操作Excel的權限不夠,配置Dcom。運 行Dcomcnfg.exe,找到Excel應用程序,配置其屬性,身份驗證級別 選"無",身份標識選"交互式用戶",安全性頁面,啟動和訪問均給 everyone。注意:查看當前進程中是否有Winword進程存在,如果有且 不能被結束,那么重啟動計算機。再次運行你的代碼即OK。這樣以后 就不會出現權限不夠的情況了。 三、調用 #region 測試Excel QuickItemCollection qic =new QuickItemCollection(); qic.GetAllInfo(); DataView dv= new DataView(); DataTable dt = new DataTable("Excel"); dt.Columns.Add("ID",System.Type.GetType("System.String")); dt.Columns.Add("ItemName",System.Type.GetType("System.String")); int qicCount=qic.Count; for(int i=0;i<qicCount;i++) { DataRow dr= dt.NewRow(); dr[0] = qic[i].ID; dr[1] = qic[i].ItemName; dt.Rows.Add(dr); } OutputExcel ope = new OutputExcel(); ope.DV=dt.DefaultView; ope.Title="測試生成Excel"; ope.InputFilePath=Server.MapPath("Sample.xls"); ope.OutFilePath=Server.MapPath("Test.xls"); ope.CreateExcel(); #endregion 一點說明:這段代碼的前半部分讀過我那篇《一種快速存取訂閱條目的方 案》的讀者應該認得的,其實也就是一個把集合類中數據填充到 DataView中的過程,后面的就是調用。Sample.xls是個新建的空的 Sample.xls,然后執行完畢后,就會生成Test.xls文檔,我執行后的 結
|