不用安裝Excel,生成原生Excel格式方法
MyXls是用C#開源項(xiàng)目,可以應(yīng)用于asp.net 或者 .net應(yīng)用程序上。它根據(jù)微軟公開的Excle文檔格式文件(BIFF),以二進(jìn)制格式直接生成excel文檔,支持Excel versions 97 - 2007 。這意味著你可以不用在服務(wù)器上安裝office就能夠以excle格式輸出數(shù)據(jù)庫中存儲(chǔ)的數(shù)據(jù)了,這對(duì)于許多項(xiàng)目來說都是很有用的。
第一步,當(dāng)然是下載MyXls,地址:http://sourceforge.net/projects/myxls/
或是在csdn資源庫下載:http://download.csdn.net/download/xianglikai1/10176118
第二步,添加引用org.in2bits.MyXls.dll
一、基礎(chǔ)使用
XlsDocument doc = new XlsDocument();
doc.FileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ".xls";
Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
Cells cells = sheet.Cells;
cells.Add(1, 1, "內(nèi)容");
doc.Save(Server.MapPath("file"));
二、列寬度設(shè)置
XlsDocument doc = new XlsDocument();
doc.FileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ".xls";
Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
Cells cells = sheet.Cells;
ColumnInfo col = new ColumnInfo(doc, sheet);
col.ColumnIndexStart = 0;
sheet.AddColumnInfo(col);
cells.Add(1, 1, "內(nèi)容");
doc.Save(Server.MapPath("file"));
三、單元格樣式設(shè)置
XlsDocument doc = new XlsDocument();
doc.FileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ".xls";
Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
Cells cells = sheet.Cells;
xf.VerticalAlignment = VerticalAlignments.Centered;
xf.HorizontalAlignment = HorizontalAlignments.Centered;
xf.PatternColor = Colors.Green;
xf.Font.FontName = "微軟雅黑";
xf.Font.Height = 20 * 20;
xf.BottomLineColor = Colors.Red;
cells.Add(1, 1, "內(nèi)容", xf);
doc.Save(Server.MapPath("file"));
四、合并單元格
XlsDocument doc = new XlsDocument();
doc.FileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ".xls";
Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
Cells cells = sheet.Cells;
MergeArea ma = new MergeArea(2, 3, 5, 7);
xf.VerticalAlignment = VerticalAlignments.Centered;
xf.HorizontalAlignment = HorizontalAlignments.Centered;
cells.Add(2, 5, "內(nèi)容", xf);
doc.Save(Server.MapPath("file"));