不用安裝Excel,生成原生Excel格式方法
MyXls是用C#開源項目,可以應用于asp.net 或者 .net應用程序上。它根據微軟公開的Excle文檔格式文件(BIFF),以二進制格式直接生成excel文檔,支持Excel versions 97 - 2007 。這意味著你可以不用在服務器上安裝office就能夠以excle格式輸出數據庫中存儲的數據了,這對于許多項目來說都是很有用的。
第一步,當然是下載MyXls,地址:http://sourceforge.net/projects/myxls/
或是在csdn資源庫下載:http://download.csdn.net/download/xianglikai1/10176118
第二步,添加引用org.in2bits.MyXls.dll
一、基礎使用
XlsDocument doc = new XlsDocument();
doc.FileName = DateTime.Now.ToString("yyyyMMddhhmmssms") + ".xls";
Worksheet sheet = doc.Workbook.Worksheets.Add("sheet1");
Cells cells = sheet.Cells;
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;
ColumnInfo col = new ColumnInfo(doc, sheet);
col.ColumnIndexStart = 0;
sheet.AddColumnInfo(col);
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;
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, "內容", 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, "內容", xf);
doc.Save(Server.MapPath("file"));