zoukankan      html  css  js  c++  java
  • NPOI读取Excel

    namespace NQJExcelHelper
    {

        public class SDExcelHelper
        {
            public static DataTable GetDataTable(string filepath)
            {
                DataTable dt = new DataTable();
                if (filepath.Last() == 's')
                {
                    dt = ExcelHelper.ExcelToTableForXLS(filepath);
                }
                else
                {
                    dt = ExcelHelper.ExcelToTableForXLSX(filepath);
                }
                return dt;
            }
            public class ExcelHelper
            {
                #region Excel2007
                /// <summary>
                /// 将Excel文件中的数据读出到DataTable中(xlsx)
                /// </summary>
                /// <param name="file"></param>
                /// <returns></returns>
                public static DataTable ExcelToTableForXLSX(string file)
                {
                    DataTable dt = new DataTable();
                    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
                        ISheet sheet = xssfworkbook.GetSheetAt(0);

                        //表头
                        IRow header = sheet.GetRow(sheet.FirstRowNum);
                        List<int> columns = new List<int>();
                        for (int i = 0; i < header.LastCellNum; i++)
                        {
                            object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
                            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)
                            {
                                if (sheet.GetRow(i) != null)
                                {
                                    dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
                                    if (dr[j] != null && dr[j].ToString() != string.Empty)
                                    {
                                        hasValue = true;
                                    }
                                }
                            }
                            if (hasValue)
                            {
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                    return dt;
                }

                /// <summary>
                /// 将DataTable数据导出到Excel文件中(xlsx)
                /// </summary>
                /// <param name="dt"></param>
                /// <param name="file"></param>
                public static void TableToExcelForXLSX(DataTable dt, string file)
                {
                    XSSFWorkbook xssfworkbook = new XSSFWorkbook();
                    ISheet sheet = xssfworkbook.CreateSheet("Test");

                    //表头
                    IRow row = sheet.CreateRow(0);
                    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 + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            ICell cell = row1.CreateCell(j);
                            cell.SetCellValue(dt.Rows[i][j].ToString());
                        }
                    }

                    //转为字节数组
                    MemoryStream stream = new MemoryStream();
                    xssfworkbook.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();
                    }
                }

                /// <summary>
                /// 获取单元格类型(xlsx)
                /// </summary>
                /// <param name="cell"></param>
                /// <returns></returns>
                private static object GetValueTypeForXLSX(XSSFCell 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:
                            if (cell.CachedFormulaResultType == CellType.Numeric)
                            {
                                return cell.NumericCellValue;
                            }
                            else
                            {
                                return cell.StringCellValue;
                            }
                        default:
                            return "=" + cell.CellFormula;
                    }
                }

                #endregion

                #region Excel2003
                public static DataTable ExcelToTableForXLS(string file)
                {
                    DataTable dt = new DataTable();
                    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
                        ISheet sheet = hssfworkbook.GetSheetAt(0);

                        //表头
                        IRow header = sheet.GetRow(sheet.FirstRowNum);
                        List<int> columns = new List<int>();
                        for (int i = 0; i < header.LastCellNum; i++)
                        {
                            object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
                            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)
                            {
                                if (sheet.GetRow(i) != null)
                                {
                                    dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
                                    if (dr[j] != null && dr[j].ToString() != string.Empty)
                                    {
                                        hasValue = true;
                                    }
                                }
                            }
                            if (hasValue)
                            {
                                dt.Rows.Add(dr);
                            }
                        }
                    }
                    return dt;

                }
                private static object GetValueTypeForXLS(HSSFCell 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:
                            if (cell.CachedFormulaResultType == CellType.Numeric)
                            {
                                return cell.NumericCellValue;
                            }
                            else
                            {
                                return cell.StringCellValue;
                            }
                        default:
                            return "=" + cell.CellFormula;
                    }
                }


                #endregion
            }
        }
    }

  • 相关阅读:
    当jsp中Springboot之登录模块探索(含Token,验证码还有数据库
    当php内容的内存分页不,如何更快的使用head的分段式处理方式
    Java 开发 2021 年发生的的一些自我总结和教训,即使反省
    总结这些年php函数中遇到的绊脚石,告别以后面试的现场尴尬
    使用 WSDL 指定的标准 SOAP 消息格式
    ORACLE数据库导出表,字段名,长度,类型,字段注释,表注释语句
    oracle中start with和connect by的用法理解
    关于RabbitMQ以及RabbitMQ和Spring的整合
    Vue.js——基于$.ajax实现数据的跨域增删查改
    HTML表格跨行、跨列操作(rowspan、colspan)
  • 原文地址:https://www.cnblogs.com/yidianfeng/p/6168490.html
Copyright © 2011-2022 走看看