目前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 =
;
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.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