• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#使用NPOI导出Excel

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作

下面介绍下NPOI操作Excel的方法

首先我们需要下载NPOI的程序集 

下载地址 http://npoi.codeplex.com/releases

我下载下来是有这两个文件

这里使用的是net4.0

将下面几个dll添加到项目中并引用

 

废话不多说  上代码

        /// <summary>
        /// create 2016-11-30 by sly 
        /// 将DataTable数据导入到excel中   此方法直接返回文件给浏览器下载
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <param name="widthDic">要设置的宽度(key 列下标,val 宽度大小)</param>
        /// <returns></returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten, Dictionary<int, int> widthDic = null)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;

            MemoryStream file = new MemoryStream();

            if (fileName.IndexOf(".xlsx") > 0) //2007版本
                workbook = new XSSFWorkbook();
            else
                if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);

                    //设置所有列宽
                    for (int l = 0; l <= data.Rows.Count; l++)
                    {
                        sheet.DefaultColumnWidth = 12;
                    }

                    if (widthDic != null)
                    {
                        //设定自定义宽度
                        foreach (var item in widthDic)
                        {
                            sheet.SetColumnWidth(item.Key, item.Value);
                        }
                    }
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }
                int outRes = -1;

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        if (int.TryParse(data.Rows[i][j].ToString(), out outRes))
                        {
                            row.CreateCell(j).SetCellValue(Convert.ToInt32(data.Rows[i][j].ToString()));
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(data.Rows[i][j].ToString()) && data.Rows[i][j].ToString().Length > 10)
                            {
                                if ((data.Rows[i][j].ToString().Substring(0, 7) == "http://" || data.Rows[i][j].ToString().Substring(0, 8) == "https://"))
                                {
                                    var TCell = row.CreateCell(j);
                                    HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.Url);//建一个HSSFHyperlink实体,指明链接类型为URL  
                                    TCell.SetCellValue(data.Rows[i][j].ToString());
                                    link.Address = data.Rows[i][j].ToString();//给HSSFHyperlink的地址赋值                                                                      
                                    TCell.Hyperlink = link;
                                }
                                else
                                {
                                    row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                                }
                            }
                            else
                            {
                                row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                            }
                        }
                    }
                    ++count;
                }
                workbook.Write(file); //写入到excel

                var context = System.Web.HttpContext.Current;
                context.Response.ContentType = "application/vnd.ms-excel";
                context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
                context.Response.Clear();
                context.Response.BinaryWrite(file.GetBuffer());
                context.Response.End();


                return count;
            }
            catch (Exception ex)
            {
                return -2;
            }
        }

 

        /// <summary>        
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns></returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else
                    if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {                
                return null;
            }
        }

 

        /// <summary>
        /// 合并单元格
        /// </summary>
        /// <param name="sheet">要合并单元格所在的sheet</param>
        /// <param name="rowstart">开始行的索引</param>
        /// <param name="rowend">结束行的索引</param>
        /// <param name="colstart">开始列的索引</param>
        /// <param name="colend">结束列的索引</param>
        public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
        {
            CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
            sheet.AddMergedRegion(cellRangeAddress);
        }

 

            //调用导出方法
            new Helper.ExcelHelper("导出的文件名.xls").DataTableToExcel(dt, "sheet1", true, null);
            new Helper.ExcelHelper("导出的文件名.xlsx").DataTableToExcel(dt, "sheet1", true, null);

 

下面是导入

<input type="file" name="fileField" class="file"  />
<script>
    $("#fileField").live("change", function () {
        var Reg = new RegExp("^.+\.(xls)");
        var Reg2 = new RegExp("^.+\.(xlsx)");
        if (Reg.test($(this).val()) || Reg.test2($(this).val())) {
            ImportGrade();//此处调用后台导入方法,这里就不写了哈
        } else {
            $.IvanDialogOpen({ "Type": "tips", "Info": "仅支持 .xls ,.xlsx 文件", "Plugins": { CloseTime: 800 } });
        }
    })
</script>
        /// <summary>
        /// 导入Demo
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public ActionResult ImportGrade(string filePath)
        {
            //获取文件在服务器上的路径
            string path = string.Concat(FileUpload.GetFilePath(UploadType.ImportGradeFile), filePath);
            //根据上传路径获取表格数据
            ExcelHelper eh = new ExcelHelper(path.Replace("\\", "/"));

            DataTable dt = eh.ExcelToDataTable("Sheet1", true);

            return Content("");
        }

 

 以上就是NPOI的简单使用方法


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#操作域用户ADHelper发布时间:2022-07-10
下一篇:
c#中SOAP序列化和反序列化发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap