不安装office导出excel

来源:互联网 发布:数控车工编程 编辑:程序博客网 时间:2024/06/05 04:45

  需求为将画面显示的datagridview 导出为excel,但客户端不安装office 。 

  开发工具为C#2008,客户使用的office为2003,折腾了一天,终于搞定。

  先实尝试了openxml来导出,发现只支持office2010。

   终于让我发现开源库org.in2bits.MyXls,真强大,实现代码如下

   

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Windows.Forms;using org.in2bits.MyXls;using System.IO;namespace ViewLayer.Class{    public class ExcelExport    {                private static ExcelExport theExcelExport = null;        public static ExcelExport Singleton        {            get            {                if (theExcelExport == null)                {                    theExcelExport = new ExcelExport();                }                return theExcelExport;            }        }                public void ExportExcelFromGrid(DataGridView theSouceGrid, string theGridName)        {            XlsDocument xls = new XlsDocument();//创建空xls文档            xls.FileName = @"C:\" + theGridName + ".xls";            Worksheet sheet = xls.Workbook.Worksheets.Add("Demo");            //创建列            Cells cells = sheet.Cells; //获得指定工作页列集合            //创建模拟数据            XF cellXF = xls.NewXF();            cellXF.Pattern = 1;            cellXF.PatternBackgroundColor = Colors.Red;//填充的背景底色            cellXF.PatternColor = Colors.Red;//设定填充线条的颜色            int iRows = theSouceGrid.Rows.Count;            int iCols = theSouceGrid.Columns.Count;            //加上列头            for (int i = 0; i < iCols - 1; i++)            {                cells.Add(1, i + 1, theSouceGrid.Columns[i].Name,cellXF);            }            //导出内容            for (int j = 1; j < iRows; j++)            {                for (int k = 1; k < iCols; k++)                {                    cells.Add(j + 1, k, theSouceGrid[k - 1, j - 1].Value );                }            }            //生成保存到服务器如果存在不会覆盖并且报异常所以先删除在保存新的            if (File.Exists(@"C:\" + theGridName + ".xls"))            {                File.Delete(@"C:\" + theGridName + ".xls");//删除            }            //File.Delete("D:" + "\\KKHMD.xls");//删除            //保存文档            xls.Save(@"C:\" + theGridName + ".xls");//保存到服务器        }            }}