Asp.net程序中生成Excel报表(转)
(转自http://www.cnblogs.com/osamede/archive/2008/04/14/1153414.html)
,生成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,生成一个空的表格
1 XlsDocument xls = new XlsDocument(); //创建一个空的Excel文档
2
3 xls.Send(); //将文档发送到浏览器。
2
3 xls.Send(); //将文档发送到浏览器。
2, 创建一个复杂点表格
XlsDocument xls = new XlsDocument();
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度
}
}
}
}
}
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度
}
}
}
}
}
效果图,一个Excel文件包含五个表格
二 XML格式
office2003或以上版本才支持xml格式,这样可以直接通过一些模板将内容转化为Office可以识别的xml,限于时间,下次再与大家讨论:-)