用MyXls生成Excel报表,C#---Good(推荐

用MyXls生成Excel报表(C#)

MyXLS 是一个快速和简单的读写 Excel 文件的 .NET 组件,可用在 ASP.NET 网站和 .NET 应用程序中,无需安装 Excel 程序,支持 Excel 97 以及以后的版本。

目前MyXls已经实现了单元格(cell)的格式设置,包括文本颜色、文本大小、字体、单位格边框、底色、列宽、行高,合并单元格,多个sheet页等功能。以下是MyXLS组件的一些用法

1.创建一个Excel文档:

XlsDocument xls = new XlsDocument();

2.创建一个WorkSheet:

Worksheet ws = xls.Workbook.Worksheets.Add("WorkSheet1");

3.指定列格式:

ColumnInfo colInfo = new ColumnInfo(xls, ws);

colInfo.ColumnIndexStart = 0;

colInfo.ColumnIndexEnd = 17;

colInfo.Width = 15 * 256;

ws.AddColumnInfo(colInfo);

列格式必须每次都要重新定义,一个列格式不能重复使用。

4.指定单元格样式:

XF xf = xls.NewXF();

xf.HorizontalAlignment = HorizontalAlignments.Centered;

xf.VerticalAlignment = VerticalAlignments.Centered;

xf.Pattern = 1;

xf.PatternColor = Colors.Default30;

xf.UseBorder = true;

xf.TopLineStyle = 1;

xf.TopLineColor = Colors.Black;

xf.BottomLineStyle = 1;

xf.BottomLineColor = Colors.Black;

xf.LeftLineStyle = 1;

xf.LeftLineColor = Colors.Black;

xf.RightLineStyle = 1;

xf.RightLineColor = Colors.Black;

xf.Font.Bold = true;

xf.Font.Height = 11 * 20;

xf.Font.ColorIndex = 1;

5.给单元格赋值:

ws.Cells.Add(2, 3, "金额(万元)", xf);

6.合并单元格:

ws.Cells.Merge(1, 2, 2, 2);

//或者

ws.AddMergeArea(new MergeArea(1, 2, 1, 1));

7.MyXls合并单元格有个bug,就是合并后只是第一个单元格有样式,其余的样式丢失。所以写了个函数来合并:

MergeRegion(ref ws, xf, "机构", 1, 1, 2, 1);

public void MergeRegion(ref Worksheet ws, XF xf, string title, int startRow, int startCol, int endRow, int endCol)

{

for (int i = startCol; i <= endCol; i++)

{

for (int j = startRow; j <= endRow; j++)

{

ws.Cells.Add(j, i, title, xf);

}

}

ws.Cells.Merge(startRow, endRow, startCol, endCol);

}

虽然效率不怎么样,但是对于出Excel报表,还OK。

8.指定单元格格式

cell.Format = StandardFormats.Decimal_1;

具体更多请参考源代码的StandardFormats类。

9.保存或者发送Excel:

xls.Send();

//或者

xls.Save();

MyXls下载地址:http://myxls.in2bits.org/Downloads.ashx

http://sourceforge.net/projects/myxls/files/

Myxls组件导入导出Excel(不需安装Excel)

使用myxls导出真正的Excel文件