• C#使用NPOI导出Excel


    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" id="fileField" value="导入" style="display: none;" />
    <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的简单使用方法

  • 相关阅读:
    编译 | 更新标准库_交叉编译工具链
    论文 | 图文_学科
    编码 | 二进制格式设计方案
    图片 | 图片上传管理
    进程 | 查询进程中包含多少线程
    第二周02:Fusion ICP逐帧融合
    exe文件当前目录搜索文件
    第一周:读取XML深度数据并将其重建为三维点云
    第二周:01 ICP迭代交互
    C++文件读写(转载)
  • 原文地址:https://www.cnblogs.com/Jian-Zhang/p/7412608.html
Copyright © 2020-2023  润新知