MyXls初级教程
這些天使用MyXls導出Excel報表(因為Apose.Cells要收費)。感覺MyXls雖然功能遠沒有Cells強大,但是勝在開源、免費而且性能穩定可靠。用作出一般情況下的報表。足矣!
記下幾個初級使用方法,希望能夠給初入門的人一點幫助:
1.創建一個Excel文檔:
CodeXlsDocument?xls?=?new?XlsDocument();
?
2.創建一個WorkSheet:
CodeWorksheet?ws?=?xls.Workbook.Worksheets.Add("WorkSheet1");
?
3.指定列格式:
CodeColumnInfo?colInfo?=?new?ColumnInfo(xls,?ws);
colInfo.ColumnIndexStart?=?0;
colInfo.ColumnIndexEnd?=?17;
colInfo.Width?=?15?*?256;
ws.AddColumnInfo(colInfo);
?
列格式必須每次都要重新定義,一個列格式不能重復使用。
?
4.指定單元格樣式:
CodeXF?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.給單元格賦值:
Codews.Cells.Add(2,?3,?"金額(萬元)",?xf);
?
6.合并單元格:
Codews.Cells.Merge(1,?2,?2,?2);
//或者
ws.AddMergeArea(new?MergeArea(1,?2,?1,?1));
?
7.MyXls合并單元格有個bug,就是合并后只是第一個單元格有樣式,其余的樣式丟失。所以寫了個函數來合并:
CodeMergeRegion(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.指定單元格格式:
Codecell.Format?=?StandardFormats.Decimal_1;
?
具體更多請參考源代碼的StandardFormats類。
?
9.保存或者發送Excel:
Codexls.Send();
//或者
xls.Save();
?
?
轉載于:https://www.cnblogs.com/KenBlove/archive/2009/09/07/1562044.html
總結
- 上一篇: 网工视频13第13章.计算机系统开发运行
- 下一篇: JSON实现桌面可移动的小便签