ExcelDataReader 仅从 XSSFWorkbook 保存的文件中读取第一列(C#)

问题描述 投票:0回答:1

ExcelDataReader 只能从 NPOI 生成的 Excel 中读取第一列(标题/数据)。

例如下面的代码,它只会读取第一列“111”和数据“444”

嗯,任何想法都很好,提前谢谢。

一个奇怪的部分是 excel.exe (2019) 保存后文件大小会发生变化。 4KB -> 10KB,不知道为什么。 *然后,ExcelDataReader 就可以完全读取该文件。

HSSFWorkbook(.xls) 也可以,希望我只丢失了很少的部分?

写:

XSSFWorkbook EWorkbook = new XSSFWorkbook();
XSSFSheet ESheet1 = (XSSFSheet)EWorkbook.CreateSheet("Test");
XSSFRow ERow = (XSSFRow)ESheet1.CreateRow(0);
XSSFCell ECell = (XSSFCell)ERow.CreateCell(0); ECell.SetCellValue("111");
ECell = (XSSFCell)ERow.CreateCell(1); ECell.SetCellValue("222");
ECell = (XSSFCell)ERow.CreateCell(2); ECell.SetCellValue("333");

ERow = (XSSFRow)ESheet1.CreateRow(1); 
ECell = (XSSFCell)ERow.CreateCell(0); ECell.SetCellValue("444");
ECell = (XSSFCell)ERow.CreateCell(1); ECell.SetCellValue("555");
ECell = (XSSFCell)ERow.CreateCell(2); ECell.SetCellValue("666");

using (var file2 = new FileStream(@"C:\inetpub\temp.xlsx", FileMode.Create, FileAccess.ReadWrite))
{
EWorkbook.Write(file2);
file2.Close();
}

阅读:

excelSpreadSheet = Excel.ExcelReaderFactory.CreateOpenXmlReader(fs);
c# npoi exceldatareader
1个回答
0
投票

以下显示如何使用 Nuget 包 NPOI (v2.6.2) 创建 .xlsx 文件,然后使用 Nuget 包 ExcelDataReader (v3.6.0) 和 ExcelDataReader.DataSet (v3.6.0) 读取该文件。它已使用 Windows 窗体应用程序 (.NET Framework) v4.8 进行了测试。

先决条件:下载并安装上述 Nuget 软件包。

使用 NPOI 创建 Excel (.xlsx) 文件。

助手NPOI

using System;
using System.Collections.Generic;
using System.IO;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace ExcelNPOITest
{

    public class SpreadSheetData
    {
        public List<SpreadSheetRow> Rows = new List<SpreadSheetRow>();
    }

    public class SpreadSheetRow
    {
        public List<SpreadSheetCell> Cells { get; set; } = new List<SpreadSheetCell>();
    }

    public class SpreadSheetCell
    {
        public object CellValue { get; set; }
    }

    public class HelperNPOI
    {
        public static void CreateExcel(string filename, SpreadSheetData data)
        {
            using (IWorkbook workbook = new XSSFWorkbook())
            {
                //create sheet
                ISheet sheet1 = workbook.CreateSheet("Sheet1");

                //add data to sheet

                if (data != null)
                {
                    //0-based indices
                    for (int i = 0; i < data.Rows.Count; i++)
                    {
                        //create row
                        IRow row = sheet1.CreateRow(i);

                        for (int j = 0; j < data.Rows[i].Cells.Count; j++)
                        {
                            ICell cell = row.CreateCell(j);

                            //set cell value
                            if (data.Rows[i].Cells[j].CellValue.GetType() == typeof(bool))
                                cell.SetCellValue((bool)data.Rows[i].Cells[j].CellValue);
                            else if (data.Rows[i].Cells[j].CellValue.GetType() == typeof(DateTime))
                                cell.SetCellValue((DateTime)data.Rows[i].Cells[j].CellValue);
                            else if (data.Rows[i].Cells[j].CellValue.GetType() == typeof(double))
                                cell.SetCellValue((double)data.Rows[i].Cells[j].CellValue);
                            else if (data.Rows[i].Cells[j].CellValue.GetType() == typeof(int))
                                cell.SetCellValue((int)data.Rows[i].Cells[j].CellValue);
                            else if (data.Rows[i].Cells[j].CellValue.GetType() == typeof(string))
                                cell.SetCellValue((string)data.Rows[i].Cells[j].CellValue);
                        }

                        using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite))
                        {
                            //save workbook
                            workbook.Write(fs);
                        }
                    }
                }
            }
        }
    }
}

用法

private void CreateExcelFile(string filename)
{
    //create new instance
    SpreadSheetData data = new SpreadSheetData();

    //add test data
    data.Rows.Add(new SpreadSheetRow()
    {
        Cells = new List<SpreadSheetCell> {
        new SpreadSheetCell() { CellValue = "Row 1 Cell 1" },
        new SpreadSheetCell() { CellValue = "Row 1 Cell 2" },
        new SpreadSheetCell() { CellValue = "Row 1 Cell 3" }
    }
    });

    data.Rows.Add(new SpreadSheetRow()
    {
        Cells = new List<SpreadSheetCell> {
        new SpreadSheetCell() { CellValue = "Row 2 Cell 1" },
        new SpreadSheetCell() { CellValue = "Row 2 Cell 2" },
        new SpreadSheetCell() { CellValue = "Row 2 Cell 3" }
    }
    });

    HelperNPOI.CreateExcel(filename, data);
}

使用 ExcelDataReader 读取 Excel (.xlsx) 文件

HelperExcelDataReader

using ExcelDataReader;
using System.Data;
using System.IO;
using System.Diagnostics;

namespace ExcelNPOITest
{
    public class HelperExcelDataReader
    {
        public static DataSet ReadDataFromExcelFile(string filename)
        {
            DataSet dataSet = new DataSet();

            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                //create new instance
                IExcelDataReader excelDataReader = ExcelDataReader.ExcelReaderFactory.CreateReader(fs);

                //get data
                dataSet = excelDataReader.AsDataSet(new ExcelDataSetConfiguration()
                {
                    UseColumnDataType = false,
                    ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                    {
                        UseHeaderRow = false
                    }
                });

                //var dataTable = dataSet.Tables[0];
            }

            return dataSet;
        }
    }
}

用法

private void DisplayDataSet(string filename)
{
    DataSet ds = HelperExcelDataReader.ReadDataFromExcelFile(filename);

    if (ds != null)
    {
        //option 1
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            foreach (var value in row.ItemArray)
            {
                Debug.WriteLine("{0}, {1}", value, value.GetType());
            }
        }

        /*
        //option 2
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            Debug.WriteLine($"DataTable: {ds.Tables[i].TableName}");

            for (int rowIndex = 0; rowIndex < ds.Tables[i].Rows.Count; rowIndex++)
            {
                Debug.Write($"row[{rowIndex}]: ");

                for (int columnIndex = 0; columnIndex < ds.Tables[i].Columns.Count; columnIndex++)
                {
                    Debug.Write($"\"{ds.Tables[i].Rows[rowIndex][columnIndex].ToString()}\" ");
                }

                Debug.WriteLine("");
            }

            Debug.WriteLine("");
        }
        */
    }
}

输出

Row 1 Cell 1, System.String
Row 1 Cell 2, System.String
Row 1 Cell 3, System.String
Row 2 Cell 1, System.String
Row 2 Cell 2, System.String
Row 2 Cell 3, System.String

资源

© www.soinside.com 2019 - 2024. All rights reserved.