• C#对Execl操作类


    1.NuGet下安装 NPOI

    2.实例代码:(可以根据具体情况注释和添加代码逻辑)

    public class ExeclHelper
    {
    /// <summary>
    /// 将excel文件内容读取到DataTable数据表中
    /// </summary>
    /// <param name="fileName">文件完整路径名</param>
    /// <param name="sheetName">指定读取excel工作薄sheet的名称</param>
    /// <param name="isFirstRowColumn">第一行是否是DataTable的列名:true=是,false=否</param>
    /// <returns>DataTable数据表</returns>
    public static DataTable ReadExcelToDataTable(string fileName, List<string> cellList, string sheetName = "Sheet", bool isFirstRowColumn = true)
    {
    if (!File.Exists(fileName))
    {
    if(!TableToExcel(new DataTable(), fileName, cellList))
    return null;
    }
    //定义要返回的datatable对象
    DataTable data = new DataTable();
    //excel工作表
    NPOI.SS.UserModel.ISheet sheet = null;
    //数据开始行(排除标题行)
    int startRow = 0;
    try
    {
    if (!File.Exists(fileName))
    {
    return null;
    }
    //根据指定路径读取文件
    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    //根据文件流创建excel数据结构
    //NPOI.SS.UserModel.IWorkbook workbook = NPOI.SS.UserModel.WorkbookFactory.Create(fs);
    //IWorkbook workbook = new HSSFWorkbook(fs);
    IWorkbook workbook;
    string fileExt = Path.GetExtension(fileName).ToLower();
    if (fileExt == ".xlsx")
    {
    workbook = new XSSFWorkbook(fs);
    }
    else if (fileExt == ".xls")
    {
    workbook = new HSSFWorkbook(fs);
    }
    else
    {
    workbook = null;
    }

    if (workbook == null)
    {
    return new DataTable();
    }
    //如果有指定工作表名称
    if (!string.IsNullOrEmpty(sheetName))
    {
    sheet = workbook.GetSheet(sheetName);
    //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
    if (sheet == null)
    {
    sheet = workbook.GetSheetAt(0);
    }
    }
    else
    {
    //如果没有指定的sheetName,则尝试获取第一个sheet
    sheet = workbook.GetSheetAt(0);
    }
    if (sheet != null)
    {
    NPOI.SS.UserModel.IRow firstRow = sheet.GetRow(0);
    //一行最后一个cell的编号 即总的列数
    int cellCount = firstRow.LastCellNum;
    //如果第一行是标题列名
    if (isFirstRowColumn)
    {
    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
    {
    NPOI.SS.UserModel.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)
    {
    NPOI.SS.UserModel.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>
    /// Datable导出成Excel
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="file">导出路径(包括文件名与扩展名)</param>
    public static bool TableToExcel(DataTable dt, string file,List<string> cellList)
    {
    try
    {
    //存在删除
    if (File.Exists(file))
    File.Delete(file);
    IWorkbook workbook;
    string fileExt = Path.GetExtension(file).ToLower();
    if (fileExt == ".xlsx")
    {
    workbook = new XSSFWorkbook();
    }
    else if (fileExt == ".xls")
    {
    workbook = new HSSFWorkbook();
    }
    else
    {
    workbook = null;
    return false;
    }
    ISheet sheet = workbook.CreateSheet("Sheet");

    //表头
    IRow row = sheet.CreateRow(0);
    for (int i = 0; i < cellList.Count; i++)
    {
    ICell cell = row.CreateCell(i);
    cell.SetCellValue(cellList[i]);
    }

    //数据
    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();
    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();
    }

    return true;
    }
    catch(Exception ex)
    {
    return false;
    }
    }
    }

    注:cellList为execl表头集合

  • 相关阅读:
    【vijos】1768 顺序对的值(特殊的技巧)
    【vijos】1789 String(组合计数+奇怪的题)
    【vijos】1790 拓扑编号(拓扑+贪心)
    【vijos】1629 八(容斥原理+dfs)
    【vijos】1543 极值问题(数论+fib数)
    【vijos】1447 开关灯泡(高精度+特殊的技巧)
    【vijos】1164 曹冲养猪(中国剩余定理)
    【vijos】1882 石阶上的砖(中位数+特殊的技巧)
    【vijos】1881 闪烁的繁星(线段树+特殊的技巧)
    【vijos】1286 座位安排(状压dp)
  • 原文地址:https://www.cnblogs.com/xiewei123/p/10902603.html
Copyright © 2020-2023  润新知