C#創(chuàng)建Excel文件實例講解
作者:shf
C#創(chuàng)建Excel文件實例講解主要向你介紹了從數(shù)據(jù)庫中導(dǎo)出并實現(xiàn)C#創(chuàng)建Excel文件,那么具體用到的方法是什么呢?那么本文就向你介紹這方面的內(nèi)容,想對你有所幫助。
從數(shù)據(jù)庫中導(dǎo)出C#創(chuàng)建Excel文件(含Interop.Excel.Dll)是我們在實際開發(fā)中遇到的問題,那么如何解決呢?是用什么方法可以實現(xiàn)呢,下面我們通過實例的演示向你具體介紹下。
C#創(chuàng)建Excel文件實現(xiàn)實例:
- //創(chuàng)建一個excel application
- Excel.Application xls_exp=null;
- int rowindex=1;
- int colindex=0;
- //創(chuàng)建一個workbook,一個worksheet
- Excel._Workbook xls_book=null;
- Excel._Worksheet xls_sheet=null;
- try
- {
- xls_exp=new Excel.ApplicationClass();
- xls_book=xls_exp.Workbooks.Add(true);
- xls_sheet=(Excel._Worksheet)xls_book.ActiveSheet;
- //C#創(chuàng)建Excel文件之取得數(shù)據(jù)
- DataTable aa=GetData();
- //將所得到的表的列名,賦值給單元格
- foreach(DataColumn col in aa.Columns)
- {
- colindex++;
- xls_exp.Cells[1,colindex]=col.ColumnName;
- //水平對齊
- xls_sheet.get_Range(xls_exp.Cells[1,colindex],
- xls_exp.Cells[1,colindex]).HorizontalAlignment=
- Excel.XlVAlign.xlVAlignCenter;
- //C#創(chuàng)建Excel文件之垂直對齊
- xls_sheet.get_Range(xls_exp.Cells[1,colindex],
- xls_exp.Cells[1,colindex]).VerticalAlignment=
- Excel.XlVAlign.xlVAlignCenter;
- //行高、列寬自適應(yīng)
- //xls_sheet.Cells.Rows.AutoFill();
- //xls_sheet.Cells.Columns.AutoFill();
- }
- //同樣方法處理數(shù)據(jù)
- foreach(DataRow row in aa.Rows)
- {
- rowindex++;
- colindex=0;
- foreach(DataColumn col in aa.Columns)
- {
- colindex++;
- switch (row[col.ColumnName].GetType().ToString())
- {
- //字符
- case ("System.String"):
- //數(shù)字格式設(shè)置為文本
- xls_sheet.get_Range(
- xls_exp.Cells[rowindex,colindex],
- xls_exp.Cells[rowindex,colindex]).NumberFormatLocal="@";
- //C#創(chuàng)建Excel文件之水平對齊
- xls_sheet.get_Range(
- xls_exp.Cells[rowindex,colindex],
- xls_exp.Cells[rowindex,colindex]).HorizontalAlignment=
- Excel.XlVAlign.xlVAlignCenter;
- //垂直對齊
- xls_sheet.get_Range(
- xls_exp.Cells[rowindex,colindex],
- xls_exp.Cells[rowindex,colindex]).VerticalAlignment=
- Excel.XlVAlign.xlVAlignCenter;
- break;
- //日期
- case("System.DateTime"):
- //數(shù)字格式設(shè)置為yyyy-mm-dd hh:mm:ss日期
- xls_sheet.get_Range(
- xls_exp.Cells[rowindex,colindex],
- xls_exp.Cells[rowindex,colindex]).
- NumberFormatLocal="YYYY-MM-DD HH:MM:SS";
- break;
- }
- //C#創(chuàng)建Excel文件之給cell賦值
- xls_exp.Cells[rowindex,colindex]=row[col.ColumnName];
- }
- }
- //不可見,即后臺處理
- xls_exp.Visible=true;
- catch(Exception err)
- {
- MessageBox.show(err.Message);
- }
- //finally
- //{
- //xls_exp.Quit();
- //}
C#創(chuàng)建Excel文件的基本內(nèi)容就向你介紹到這里,希望對你了解C#創(chuàng)建Excel文件有所幫助。
【編輯推薦】
責(zé)任編輯:仲衡
來源:
博客園