在後台調用excel組件,產生Excel,雖然可以對Excel檔案進行完全控制,可以產生任何複雜的格式,但是有個很大的缺點,這種方式會產生很多Excel進程,很難完全清除掉,特別是在出錯的時候,可能會使整個伺服器崩潰。本文為大家介紹一個C#寫的開源組件,並簡單說下office2003和以上版本支援的XML格式。
一 操作Excel二進位格式
OpenOffice.org發布過的倆個文檔Excel File Format (BIFF8)Specification和Microsoft CompoundDocument (OLE2) Format Specification對Excel的二進位格式做了一個比較詳細的說明,依靠這些資訊,我們可以直接操作Office二進位格式文檔。
MyXls是一個C#寫的開源組件,可以用來產生具有很多表格且包含格式的Excel檔案。它提供了一套基於對象的API,非常容易使用。
MyXls這個組件的DLL 和代碼 可以在這下載到:
http://sourceforge.net/project/showfiles.php?group_id=205384&package_id=245371
以下是一個案例子。。
protected void Page_Load(object sender, EventArgs e)
{
string strSql = "SELECT TRADE_DATE [Date],TOPEN [Open],Thigh High,tlow [Low] FROM DAY_QUOTATION where SEC_CODE='1' and TRADE_DATE>='20070411' order by TRADE_DATE desc"; //Sql語句
DataSet ds = SqlHandle.ExecuteReturnDataSet(CommandType.Text, strSql, null);
xlsGridview(ds, "data");//調用xlsGridview方法產生Excel報表
}
/**//// <summary>
/// 綁定資料庫產生XLS報表
/// </summary>
/// <param name="ds">擷取DataSet資料集</param>
/// <param name="xlsName">報表表名</param>
private void xlsGridview(DataSet ds, string xlsName)
{
XlsDocument xls = new XlsDocument();
int rowIndex = 1;
int colIndex = 0;
System.Data.DataTable table = ds.Tables[0];
Worksheet sheet = xls.Workbook.Worksheets.AddNamed("sheet");//狀態列標題名稱
Cells cells = sheet.Cells;
foreach (DataColumn col in table.Columns)
{
colIndex++;
//sheet.Cells.AddValueCell(1,colIndex,col.ColumnName);//添加XLS標題列
cells.AddValueCell(1, colIndex,col.ColumnName);
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
//sheet.Cells.AddValueCell(rowIndex, colIndex, row[col.ColumnName].ToString());//將資料添加到xls表格裡
Cell cell= cells.AddValueCell(rowIndex, colIndex, Convert.ToDouble(row[col.ColumnName].ToString()));//轉換為數字型
//如果你資料庫裡的資料都是數位話 最好轉換一下,不然匯入到Excel裡是以字串形式顯示。
cell.Font.FontFamily = FontFamilies.Roman; //字型
cell.Font.Bold = true; //字型為粗體
}
}
xls.Send();
}