读取Excel文件(.xls/.xlsx)的最佳方式

zrfyljdw  于 2023-02-20  发布在  其他
关注(0)|答案(8)|浏览(593)

我知道有不同的方法来读取Excel文件:

  • Iterop
  • Oledb
  • Open Xml SDK

兼容性不是问题,因为程序将在受控环境中执行。
我的要求:
将文件读取到DataTable/CUstom Entitie(我不知道如何为对象创建动态属性/字段[列名称在Excel文件中会发生变化])
使用DataTable/Custom Entities可以使用其数据执行某些操作。
使用操作结果更新DataTable
将其写回excel file
那样就简单多了。
如果可能的话,也建议我自定义实体(动态添加属性/字段到对象)

ql3eal8s

ql3eal8s1#

看一下Linq-to-Excel,它非常简洁。

var book = new LinqToExcel.ExcelQueryFactory(@"File.xlsx");

var query =
    from row in book.Worksheet("Stock Entry")
    let item = new
    {
        Code = row["Code"].Cast<string>(),
        Supplier = row["Supplier"].Cast<string>(),
        Ref = row["Ref"].Cast<string>(),
    }
    where item.Supplier == "Walmart"
    select item;

它还允许强类型行访问。

c9x0cxw0

c9x0cxw02#

我知道这个问题是问了近7年前,但它仍然是谷歌搜索结果的某些关键字有关导入Excel数据与C#,所以我想提供一个替代的基础上,一些最新的技术发展.
导入Excel数据已经成为我日常工作中的一项常见任务,我已经简化了这个过程,并在我的博客上记录了该方法:best way to read excel file in c#.
我使用NPOI是因为它可以在没有安装Microsoft Office的情况下读写Excel文件,而且它不使用COM+或任何互操作。这意味着它可以在云中工作!
但真正的魔力来自于与NPOI Mapper from Donny Tian的配对,因为它允许我将Excel列Map到C#类中的属性,而无需编写任何代码。
基本思路如下:
我创建了一个. net类,它匹配/Map了我感兴趣的Excel列:

class CustomExcelFormat
        {
            [Column("District")]
            public int District { get; set; }

            [Column("DM")]
            public string FullName { get; set; }

            [Column("Email Address")]
            public string EmailAddress { get; set; }

            [Column("Username")]
            public string Username { get; set; }

            public string FirstName
            {
                get
                {
                    return Username.Split('.')[0];
                }
            }

            public string LastName
            {
                get
                {
                    return Username.Split('.')[1];
                }
            }
        }

注意,如果我愿意,它允许我根据列名进行Map!
然后,当我处理excel文件时,我需要做的就是这样的事情:

public void Execute(string localPath, int sheetIndex)
        {
            IWorkbook workbook;
            using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
            {
                workbook = WorkbookFactory.Create(file);
            }

            var importer = new Mapper(workbook);
            var items = importer.Take<CustomExcelFormat>(sheetIndex);
            foreach(var item in items)
            {
                var row = item.Value;
                if (string.IsNullOrEmpty(row.EmailAddress))
                    continue;

                UpdateUser(row);
            }

            DataContext.SaveChanges();
        }

现在,不可否认的是,我的代码并没有修改Excel文件本身,而是使用Entity Framework将数据保存到数据库中(这就是为什么在我的示例中会看到"UpdateUser"和"SaveChanges")。

6uxekuva

6uxekuva3#

使用OLE查询非常简单(例如sheetName为Sheet1):

DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{           
    DataTable sheetData = new DataTable();
    using (OleDbConnection conn = this.returnConnection(fileName))
    {
       conn.Open();
       // retrieve the data using data adapter
       OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
       sheetAdapter.Fill(sheetData);
       conn.Close();
    }                        
    return sheetData;
}

private OleDbConnection returnConnection(string fileName)
{
    return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}

对于较新的Excel版本:

return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");

你也可以使用CodePlex上的一个开源项目Excel Data Reader。它在从Excel工作表导出数据方面效果非常好。
链接上给出的示例代码指定:

FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();

//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}

//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();

参考:How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

jmp7cifd

jmp7cifd4#

尝试使用此免费方式https://freenetexcel.codeplex.com

Workbook workbook = new Workbook();

 workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
 //Initialize worksheet
 Worksheet sheet = workbook.Worksheets[0];

 DataTable dataTable = sheet.ExportDataTable();
bpzcxfmw

bpzcxfmw5#

如果您可以将其限制为(Open Office XML格式)*.xlsx文件,那么最流行的库可能是EPPLus
额外的好处是,没有其他依赖项。只需使用nuget安装:

Install-Package EPPlus
1aaf6o9v

1aaf6o9v6#

尝试使用Aspose. cells库(不是免费的,但试用就足够阅读了),它相当不错

    • 一月一日**

下面是示例代码:

using Aspose.Cells;
using System;

namespace ExcelReader
{
    class Program
    {
        static void Main(string[] args)
        {
            // Replace path for your file
            readXLS(@"C:\MyExcelFile.xls"); // or "*.xlsx"
            Console.ReadKey();
        }

        public static void readXLS(string PathToMyExcel)
        {
            //Open your template file.
            Workbook wb = new Workbook(PathToMyExcel);

            //Get the first worksheet.
            Worksheet worksheet = wb.Worksheets[0];

            //Get cells
            Cells cells = worksheet.Cells;

            // Get row and column count
            int rowCount = cells.MaxDataRow;
            int columnCount = cells.MaxDataColumn;

            // Current cell value
            string strCell = "";

            Console.WriteLine(String.Format("rowCount={0}, columnCount={1}", rowCount, columnCount));

            for (int row = 0; row <= rowCount; row++) // Numeration starts from 0 to MaxDataRow
            {
                for (int column = 0; column <= columnCount; column++)  // Numeration starts from 0 to MaxDataColumn
                {
                    strCell = "";
                    strCell = Convert.ToString(cells[row, column].Value);
                    if (String.IsNullOrEmpty(strCell))
                    {
                        continue;
                    }
                    else
                    {
                        // Do your staff here
                        Console.WriteLine(strCell);
                    }
                }
            }
        }
    }
}
pftdvrlh

pftdvrlh7#

从excel读取、修改并写回

/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
    var _xl = new Excel.Application();
    var wb = _xl.Workbooks.Open(filename);
    var sheets = wb.Sheets;
    DataSet dataSet = null;
    if (sheets != null && sheets.Count != 0)
    {
        dataSet = new DataSet();
        foreach (var item in sheets)
        {
            var sheet = (Excel.Worksheet)item;
            DataTable dt = null;
            if (sheet != null)
            {
                dt = new DataTable();
                var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                for (int j = 0; j < ColumnCount; j++)
                {
                    var cell = (Excel.Range)sheet.Cells[1, j + 1];
                    var column = new DataColumn(headers ? cell.Value : string.Empty);
                    dt.Columns.Add(column);
                }

                for (int i = 0; i < rowCount; i++)
                {
                    var r = dt.NewRow();
                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                        r[j] = cell.Value;
                    }
                    dt.Rows.Add(r);
                }

            }
            dataSet.Tables.Add(dt);
        }
    }
    _xl.Quit();
    return dataSet;
}


 public string Export(DataTable dt, bool headers = false)
    {
        var wb = _xl.Workbooks.Add();
        var sheet = (Excel.Worksheet)wb.ActiveSheet;
        //process columns
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var col = dt.Columns[i];
            //added columns to the top of sheet
            var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
            currentCell.Value = col.ToString();
            currentCell.Font.Bold = true;
            //process rows
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                var row = dt.Rows[j];
                //added rows to sheet
                var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
                cell.Value = row[i];
            }
            currentCell.EntireColumn.AutoFit();
        }
        var fileName="{somepath/somefile.xlsx}";
        wb.SaveCopyAs(fileName);
        _xl.Quit();
        return fileName;
    }
mv1qrgav

mv1qrgav8#

我使用Office的NuGet包:DocumentFormat.OpenXml并将该组件的doc site中的代码拼凑在一起。
有了下面的帮助代码,在复杂性上类似于我在那个项目中的其他CSV文件格式解析...

public static async Task ImportXLSX(Stream stream, string sheetName) {
{
    // This was necessary for my Blazor project, which used a BrowserFileStream object
    MemoryStream ms = new MemoryStream();
    await stream.CopyToAsync(ms);

    using (var document = SpreadsheetDocument.Open(ms, false))
    {
        // Retrieve a reference to the workbook part.
        WorkbookPart wbPart = document.WorkbookPart;

        // Find the sheet with the supplied name, and then use that 
        // Sheet object to retrieve a reference to the first worksheet.
        Sheet theSheet = wbPart?.Workbook.Descendants<Sheet>().Where(s => s?.Name == sheetName).FirstOrDefault();

        // Throw an exception if there is no sheet.
        if (theSheet == null)
        {
            throw new ArgumentException("sheetName");
        }

        WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
        // For shared strings, look up the value in the
        // shared strings table.
        var stringTable = 
            wbPart.GetPartsOfType<SharedStringTablePart>()
            .FirstOrDefault();

        // I needed to grab 4 cells from each row
        // Starting at row 11, until the cell in column A is blank
        int row = 11;

        while (true) {
                var accountNameCell = GetCell(wsPart, "A" + row.ToString());
                var accountName = GetValue(accountNameCell, stringTable);
                if (string.IsNullOrEmpty(accountName)) {
                    break;
                }
                var investmentNameCell = GetCell(wsPart, "B" + row.ToString());
                var investmentName = GetValue(investmentNameCell, stringTable);
                var symbolCell = GetCell(wsPart, "D" + row.ToString());
                var symbol = GetValue(symbolCell, stringTable);
                var marketValue = GetCell(wsPart, "J" + row.ToString()).InnerText;
                
                // DO STUFF with data

                row++;
        }
    }
}

private static string? GetValue(Cell cell, SharedStringTablePart stringTable) {
    try {
        return stringTable.SharedStringTable.ElementAt(int.Parse(cell.InnerText)).InnerText;
    } catch (Exception) {
        return null;
    }
}
private static Cell GetCell(WorksheetPart wsPart, string cellReference) {
    return wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference.Value == cellReference)?.FirstOrDefault();
}

相关问题