在後臺調用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,非常容易使用。
1,生成一個空的表格
2
3 xls.Send(); // 將文檔發送到瀏覽器。
2, 創建一個複雜點表格
xls.FileName = " Wacky.xls " ;
// 添加文件屬性
xls.SummaryInformation.Author = " Tim Erickson " ; // 作者
xls.SummaryInformation.Subject = " A wacky display of Excel file generation " ;
xls.DocumentSummaryInformation.Company = " in2bits.org " ;
for ( int sheetNumber = 1 ; sheetNumber <= 5 ; sheetNumber ++ )
{
string sheetName = " Sheet " + sheetNumber;
int rowMin = sheetNumber;
int rowCount = sheetNumber + 10 ;
int colMin = sheetNumber;
int colCount = sheetNumber + 10 ;
// 創建5個表格
Worksheet sheet = xls.Workbook.Worksheets.AddNamed(sheetName);
Cells cells = sheet.Cells;
for ( int r = 0 ; r < rowCount; r ++ )
{
if (r == 0 )
{
for ( int c = 0 ; c < colCount; c ++ )
{
// 在一行內創建colCount個單元格
cells.Add(rowMin + r, colMin + c, " Fld " + (c + 1 )).Font.Bold = true ;
}
}
else
{
for ( int c = 0 ; c < colCount; c ++ )
{
int val = r + c;
Cell cell = cells.Add(rowMin + r, colMin + c, val);
if (val % 2 != 0 )
{
cell.Font.FontName = " Times New Roman " ;
cell.Font.Underline = UnderlineTypes.Double; // 給文字下方加一個雙下劃線
cell.Rotation = 45 ; // 單元格文字旋轉45度
}
}
}
}
}
二 XML格式
office2003或以上版本才支持xml格式,這樣可以直接通過一些模板將內容轉化爲Office可以識別的xml,限於時間,下次再與大家討論:-)