不用安装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"));