zoukankan      html  css  js  c++  java
  • 用npoi生成excel

    用npoi生成excel的文章已经有很多,我这就不多说了,今天主要的目的就是把我写的例子贴出来和大家分享

    如果有不明白的地方,可以联系我

    public static string ExportExcel(DataTable dtSource, string AppSettingPath,string Aid)
            {
                try
                {
                    string AdPath = string.Empty;
                    string FileName = string.Empty;
                    HSSFWorkbook workbook = new HSSFWorkbook();
                    HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
                    //填充表头
                    HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
                    foreach (DataColumn column in dtSource.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName == "");
                    }
    
    
                    //填充内容
                    for (int i = 0; i < dtSource.Rows.Count; i++)
                    {
                        dataRow = (HSSFRow)sheet.CreateRow(i + 1);
                        for (int j = 0; j < dtSource.Columns.Count; j++)
                        {
                            dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                        }
                    }
    
    
                    //保存
                    using (MemoryStream ms = new MemoryStream())
                    {
                        // FileName=DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";
                        FileName = Aid + ".xls";
                        AdPath = System.Web.HttpContext.Current.Server.MapPath(AppSettingPath) + FileName;
                        using (FileStream fs = new FileStream(AdPath, FileMode.Create, FileAccess.Write))
                        {
                            workbook.Write(fs);
                        }
                    }
                    workbook.Dispose();
                    if (FileName != string.Empty)
                    { return CmsUrl + AppSettingPath + FileName; }
                    else { return string.Empty; }
                }
                catch(Exception ex)
                {
                    throw new Exception(ex.Message,ex);
                }
            }
    
    这边 HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); 有用到个类型转换,如果不强制转换,会报错,网上的很多demo就是因为没有转换,所有在run的时候,报错了..

  • 相关阅读:
    后缀树到后缀自动机
    bzoj 4199 品酒大会
    BZOJ 4310 跳蚤
    BZOJ 4545 DQS的Trie
    BZOJ 3238 差异
    BZOJ 3277 串
    BZOJ 3926 诸神眷顾的幻想乡
    线程与进程
    SparkSql自定义数据源之读取的实现
    spark提交至yarn的的动态资源分配
  • 原文地址:https://www.cnblogs.com/_fyz/p/1886668.html
Copyright © 2011-2022 走看看