MyXLS 是一個(gè)快速和簡單的讀寫 Excel 文件的 .NET 組件,可用在 ASP.NET 網(wǎng)站和 .NET 應(yīng)用程序中,無需安裝 Excel 程序,支持 Excel 97 以及以后的版本。
目前MyXls已經(jīng)實(shí)現(xiàn)了單元格(cell)的格式設(shè)置,包括文本顏色、文本大小、字體、單位格邊框、底色、列寬、行高,合并單元格,多個(gè)sheet頁等功能。以下是MyXLS組件的一些用法:
1.創(chuàng)建一個(gè)Excel文檔:
XlsDocument xls = new XlsDocument();
2.創(chuàng)建一個(gè)WorkSheet:
Worksheet ws = xls.Workbook.Worksheets.Add("WorkSheet1");
3.指定列格式:
ColumnInfo colInfo = new ColumnInfo(xls, ws);
colInfo.ColumnIndexStart = ;
colInfo.ColumnIndexEnd = 17;
colInfo.Width = 15 * 256;
ws.AddColumnInfo(colInfo);
列格式必須每次都要重新定義,一個(gè)列格式不能重復(fù)使用。
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合并單元格有個(gè)bug,就是合并后只是第一個(gè)單元格有樣式,其余的樣式丟失。所以寫了個(gè)函數(shù)來合并:
MergeRegion(ref ws, xf, "機(jī)構(gòu)", 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);
}
雖然效率不怎么樣,但是對(duì)于出Excel報(bào)表,還OK。
8.指定單元格格式:
cell.Format = StandardFormats.Decimal_1;
具體更多請(qǐng)參考源代碼的StandardFormats類。
9.保存或者發(fā)送Excel: