【问题标题】:How to read Excel file (Header only) data如何读取 Excel 文件(仅标题)数据
【发布时间】:2020-03-18 05:09:56
【问题描述】:

我想从 Excel 的列标题中读取数据。 每个 excel 文件具有相同的标题名称,但标题名称位于不同的行中。 请在 c# 代码中帮助我。 我的代码如下。

 var textfile = Request.Files[0];
        string profileimage = Path.GetExtension(textfile.FileName);           
        string ProfileName = path.GetFileNameWithoutExtension(textfile.FileName);
        IExcelDataReader excelReader;     
     excelReader=ExcelReaderFactory.CreateBinaryReader(textfile.InputStream);
         DataSet result = excelReader.AsDataSet();
         DataTable dt = result.Tables[0];
         int Tcount = dt.Rows.Count;
         for (int i = 2; i < dt.Rows.Count; i++)
            {}

...

【问题讨论】:

  • 到目前为止你尝试过什么?请显示您到目前为止已实现的代码。
  • 编辑完成。请检查我的问题

标签: c# excel


【解决方案1】:

尝试使用 OpenXML SDK。在这里您可以找到更多信息:

  1. StackOverflow
  2. Microsoft Docs
  3. NuGet
  4. GitHub

【讨论】:

    【解决方案2】:

    一种方法是使用互操作。这是办公室自带的,所以你不需要任何第三方的东西。

    using Excel=Microsoft.Office.Interop.Excel; 
    
    // Start Excel.exe
    MyApp = new Excel.Application();
    // Hide the visual application, you can also choose to omit this to show the excel application while your code works on it.
    MyApp.Visible = false;
    // Open the file
    MyBook = MyApp.Workbooks.Open("Some/Excel/File");
    // Get the first sheet
    MySheet = MyBook.Sheets[1];
    // Get some cell value
    MyCell= MySheet.Cells[rowIndex,colIndex]
    

    然后您可以遍历行以通过行/列索引或字符串比较来查找标题。 最后你需要用这个来释放 COM 对象(这里的顺序很重要),否则 Excel.exe 将继续运行:

    Marshal.ReleaseComObject(MyCell);
    Marshal.ReleaseComObject(MySheet);
    Marshal.ReleaseComObject(MyBook);
    Marshal.ReleaseComObject(MyApp);
    

    请务必先阅读文档,因为在使用互操作时存在一些问题,例如释放对象。

    猜你喜欢
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多