【问题标题】:The solution to read excel by using C#使用C#读取excel的解决方案
【发布时间】:2016-05-23 08:26:53
【问题描述】:

情况:

我正在使用 C#,我需要从 excel 文件中读取内容。 excel 文件中的内容将与图像相似。

The first column is the criteria, and the second column is the amount of the criteria. These content will have more than 1000 rows and will be placed at the last sheet of the excel file.

我正在尝试使用 File Helper 从 excel 中读取内容。 但是从提供的示例中,我只知道我可以读取文本文件,但不能读取 excel 文件。

问题:

  1. 有没有更好的例子来告诉我如何使用 FileHelpers 从 excel 中读取内容?
  2. 还有其他更好的解决方案带有示例可以帮助我从 excel 中读取内容。请指导我。

【问题讨论】:

  • 我认为您没有正确尝试应该在网上搜索并找到很多示例..试试这个stackoverflow.com/questions/657131/…
  • 它是 xlsx 还是 xls 文件?旧格式还是新格式?
  • 在阅读excel文件时,我倾向于使用OleDb,所以我可以使用sql查询。例如:CodeProject
  • @Manish 感谢您重定向我。
  • @Thorarins 应该可以处理新旧格式。

标签: c# excel


【解决方案1】:

您可以为此 ExcelToEnumerable。这是一个例子:

首先定义一个代表一行电子表格数据的类。在你的情况下,它可能是这样的:

public class SpreadsheetRow
{
    public string Category { get; set; }
    public int Frequency { get; set; }
}

然后使用ExcelToEnumerable将电子表格数据转换成IEnumerable类型为SpreadsheetRow

var filePath = "../Path/To/Spreadsheet.xlsx";
IEnumerable<SpreadsheetRow> result = filePath.ExcelToEnumerable<SpreadsheetRow>(x => x.UsingHeaderNames(false)
    .Property(y => y.Category).UsesColumnNumber(0)
    .Property(y => y.Frequency).UsesColumnNumber(1));

免责声明:我是 ExcelToEnumerable 的作者

【讨论】:

    【解决方案2】:

    我认为您应该使用 OpenXML,它会为您提供 Datatable 格式的 Excel 数据,以后您可以根据自己的意愿使用。

    static void Main(string[] args)
    {
        DataTable dt = new DataTable();
    
        using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"..\..\example.xlsx", false))
        {
    
            WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
            IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
            string relationshipId = sheets.First().Id.Value;
            WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
            Worksheet workSheet = worksheetPart.Worksheet;
            SheetData sheetData = workSheet.GetFirstChild<SheetData>();
            IEnumerable<Row> rows = sheetData.Descendants<Row>();
    
            foreach (Cell cell in rows.ElementAt(0))
            {
                dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
            }
    
            foreach (Row row in rows) //this will also include your header row...
            {
                DataRow tempRow = dt.NewRow();
    
                for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                {
                    tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i-1));
                }
    
                dt.Rows.Add(tempRow);
            }
    
        }
        dt.Rows.RemoveAt(0); //...so i'm taking it out here.
    
    }
    
    
    public static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
        SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
        string value = cell.CellValue.InnerXml;
    
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
        }
        else
        {
            return value;
        }
    }
    

    注意:参考From Excel to DataTable in C# with Open XML

    【讨论】:

      【解决方案3】:

      您可以使用 Microsoft.Office.Interop.Excel 库来读取 Excel。您可以在附加的链接中找到完整的过程

      How to read from Excel in C#

      using System;
      using System.Windows.Forms;
      using Excel = Microsoft.Office.Interop.Excel; 
      
      namespace WindowsApplication1
      {
          public partial class Form1 : Form
          {
              public Form1()
              {
                  InitializeComponent();
              }
      
              private void button1_Click(object sender, EventArgs e)
              {
                  Excel.Application xlApp ;
                  Excel.Workbook xlWorkBook ;
                  Excel.Worksheet xlWorkSheet ;
                  Excel.Range range ;
      
                  string str;
                  int rCnt = 0;
                  int cCnt = 0;
      
                  xlApp = new Excel.Application();
                  xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                  xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
      
                  range = xlWorkSheet.UsedRange;
      
                  for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
                  {
                      for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                      {
                          str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2 ;
                          MessageBox.Show(str);
                      }
                  }
      
                  xlWorkBook.Close(true, null, null);
                  xlApp.Quit();
      
                  releaseObject(xlWorkSheet);
                  releaseObject(xlWorkBook);
                  releaseObject(xlApp);
              }
      
              private void releaseObject(object obj)
              {
                  try
                  {
                      System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                      obj = null;
                  }
                  catch (Exception ex)
                  {
                      obj = null;
                      MessageBox.Show("Unable to release the Object " + ex.ToString());
                  }
                  finally
                  {
                      GC.Collect();
                  }
              } 
      
          }
      }
      

      【讨论】:

      • 将链接中的相关代码复制到您的答案中,仅链接的答案是错误的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 2013-04-24
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-10
      • 2019-02-16
      相关资源
      最近更新 更多