C# NPOI操作Excel

首先NuGet 搜索NPOI并安装
下面是一个转换为DataTable的类 file 为文件路径 index 为sheet

public static class ExcelTools
    {
        public static DataTable ExcelToTable(string file, int index)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                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(index);
                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;
        }
        public static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return null;
                case CellType.Boolean:
                    return cell.BooleanCellValue;
                case CellType.Numeric:
                    return cell.NumericCellValue;
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Error:
                    return cell.ErrorCellValue;
                case CellType.Formula:
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }

窗体代码 B/S跳过 选择xls 文件

            OpenFileDialog fileDialog = new OpenFileDialog
            {
                Multiselect = true,
                Title = "请选择文件",
                Filter = "所有文件(*xls*)|*.xls*"
            };
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                var filePath = fileDialog.FileName;
                this.txtPath.Text = filePath;
            }
            fileDialog.Dispose();


Excel的读取
读取第一个sheet

  var table = ExcelTools.ExcelToTable(this.txtPath.Text, 0);
  for (int i = 0; i < table.Rows.Count; i++)
      { 
      	//第一行的第一个单元格 以此类推
      	table.Rows[i].ItemArray[0].ToString(),
      	//后续新增操作略过
      }

Excel的写入

				var disCell = new string[] { "计划", "货主",  "货品", "进门时间", "出门时间", "编辑人姓名" };

 				IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet("onesheet");
                IRow row0 = sheet.CreateRow(0);

                for (int i = 0; i < disCell.Length; i++)
                {
                    row0.CreateCell(i).SetCellValue(disCell[i]);
                }
                for (int r = 0; r < lstBizWeigh.Count; r++)
                {
                    IRow row = sheet.CreateRow(r+1);
                    row.CreateCell(0).SetCellValue(list[r].xxx);
                    row.CreateCell(1).SetCellValue(list[r].xxx);
                }

你可能感兴趣的:(C#)