zoukankan      html  css  js  c++  java
  • 通过NPOI插件完成Excel和DataTable的互相转换,兼容xlsx和xls

    这次我们通过NPOI插件来完成Excel的导入和导出

    这个插件的好处有两个:

    1.兼容xls和xlsx,这两种后缀的都能打开

    2.服务器可以不用安装office,也就不需要考虑office版本的问题

    下载NPOI插件

    插件下载解压以后有两个版本,Net20和Net40,分别对应的是.net2.0版本和.net4.0版本

    这里用的是Net40,打开以后里面有5个dll,需要把他们都引用进来

    引用进来以后,需要再代码里添加引用,主要引用下面4个

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using NPOI.SS.Util;

    1.导入Excel代码,将Excel内容转换为DataTable

    /// <summary>
            /// Excel导入成Datable
            /// </summary>
            /// <param name="file">上传的Excel路径</param>
            /// <returns></returns>
            public static DataTable ExcelToTable(string file)
            {
                DataTable dt = new DataTable();
                IWorkbook workbook;
                string fileExt = Path.GetExtension(file).ToLower();
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                    if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                    if (workbook == null) { return null; }
                    ISheet sheet = workbook.GetSheetAt(0);
    
                    //表头  
                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    List<int> columns = new List<int>();
                    for (int i = 0; i < header.LastCellNum; i++)
                    {
                        object obj = GetValueType(header.GetCell(i));
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                        }
                        else
                            dt.Columns.Add(new DataColumn(obj.ToString()));
                        columns.Add(i);
                    }
                    //数据  
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                    {
                        DataRow dr = dt.NewRow();
                        bool hasValue = false;
                        foreach (int j in columns)
                        {
                            dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                            if (dr[j] != null && dr[j].ToString() != string.Empty)
                            {
                                hasValue = true;
                            }
                        }
                        if (hasValue)
                        {
                            dt.Rows.Add(dr);
                        }
                    }
                }
                return dt;
            }
    
    /// <summary>
            /// 获取单元格类型
            /// </summary>
            /// <param name="cell"></param>
            /// <returns></returns>
            public static object GetValueType(ICell cell)
            {
                if (cell == null)
                    return null;
                switch (cell.CellType)
                {
                    case CellType.Blank: //BLANK:  
                        return null;
                    case CellType.Boolean: //BOOLEAN:  
                        return cell.BooleanCellValue;
                    case CellType.Numeric: //NUMERIC:  
                        return cell.NumericCellValue;
                    case CellType.String: //STRING:  
                        return cell.StringCellValue;
                    case CellType.Error: //ERROR:  
                        return cell.ErrorCellValue;
                    case CellType.Formula: //FORMULA:  
                    default:
                        return "=" + cell.CellFormula;
                }
            }
    View Code

    2.导出Excel代码,将DataTable转换为Excel

            /// <summary>
            /// Datable导出成Excel
            /// </summary>
            /// <param name="dt"></param>
            /// <param name="file"></param>
            public static void TableToExcel(DataTable dt, string file, string category)
            {
                IWorkbook workbook;
                string fileExt = Path.GetExtension(file).ToLower();
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
                if (workbook == null) { return; }
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
                
                //Excel在第一行插入一行
                IRow rowTop = sheet.CreateRow(0);
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 7));//合并单元格(起始行,结束行,起始列,结束列)
                ICell cellTop = rowTop.CreateCell(0);
                cellTop.SetCellValue(category);
    
                //表头  
                IRow row = sheet.CreateRow(1);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dt.Columns[i].ColumnName);
                }
    
                //数据  
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow row1 = sheet.CreateRow(i + 2);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = row1.CreateCell(j);
                        cell.SetCellValue(dt.Rows[i][j].ToString());
                    }
                }
    
                //设置列的宽度,第一个参数表示第几列(从第0列开始),第二个参数是字符数长度
                sheet.SetColumnWidth(0, 10 * 256);
                sheet.SetColumnWidth(1, 40 * 256);
                sheet.SetColumnWidth(2, 40 * 256);
                sheet.SetColumnWidth(3, 20 * 256);
                sheet.SetColumnWidth(4, 20 * 256);
                sheet.SetColumnWidth(5, 30 * 256);
                sheet.SetColumnWidth(6, 30 * 256);
                sheet.SetColumnWidth(7, 50 * 256);
    
                //转为字节数组  
                MemoryStream stream = new MemoryStream();
                workbook.Write(stream);
                var buf = stream.ToArray();
    
                //保存为Excel文件  
                using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                }
            }     
    View Code
  • 相关阅读:
    SAP库存账龄分析报表
    elasticsearch 同义词配置搜索
    elasticsearch 上下文
    git 修改源路径 修改项目地址
    intellij IDEA 无限试用
    Kubernetes 安装Redis集群
    helm安装ingress
    安装Helm
    Kubernetes Rook + Ceph
    GIT 将工作区恢复到上次提交的内容 commit your changes or stash them before you can merge Your local changes to the following files would be overwritten by merge
  • 原文地址:https://www.cnblogs.com/zfylzl/p/6951222.html
Copyright © 2011-2022 走看看