简体   繁体   English

从Excel文件读取数据

[英]Read data from an Excel file

I searched the official documentation, but it is focused on creating the Excel file and not on reading. 我搜索了官方文档,但重点是创建Excel文件而不是阅读。 Any code snippet as an example will help me! 任何代码片段都将对我有所帮助!

How do I read Excel data? 如何读取Excel数据?

COMPANY     | DOCUMENT  | 
COMPANYONE  | 123455986 | 
COMPANYTWO  | 123455986 |
COMPANYTHREE| 123455986 |

Or use Excel Interop: 或使用Excel Interop:

using Microsoft.Office.Interop.Excel;

... ...

        Microsoft.Office.Interop.Excel.Application xl = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook workbook = xl.Workbooks.Open(@"C:\test.xlsx");
        Microsoft.Office.Interop.Excel.Worksheet sheet = workbook.Sheets[1];


        int numRows = sheet.UsedRange.Rows.Count;
        int numColumns = 2;     // according to your sample

        List<string[]> contents = new List<string[]>();
        string [] record = new string[2];

        for (int rowIndex = 1; rowIndex <= numRows; rowIndex++)  // assuming the data starts at 1,1
        {
            for (int colIndex = 1; colIndex <= numColumns; colIndex++)
            {
                Range cell = (Range)sheet.Cells[rowIndex, colIndex];
                if (cell.Value != null)
                {
                    record[colIndex-1] = Convert.ToString( cell.Value);
                }
            }
            contents.Add(record);
        }

        xl.Quit();
        Marshal.ReleaseComObject(xl);

I have had the same issue a while ago. 我前一段时间也遇到过同样的问题。

I used this solution to Read Data From an Excel File (.xls) in ASP.NET: http://www.dotnetcurry.com/ShowArticle.aspx?ID=138 . 我使用此解决方案从ASP.NET中的Excel文件(.xls)读取数据: http : //www.dotnetcurry.com/ShowArticle.aspx ?ID=138。

Simply read the range via SQL and post it into a GridView on the webpage. 只需通过SQL读取范围并将其发布到网页上的GridView中即可。

It looked to me simpler to understand for a not experienced ASP.NET/C# developer. 对于没有经验的ASP.NET/C#开发人员来说,它看起来更容易理解。

Here is a method that will read csv and excel data, and return as datatable 这是一种将读取csv和excel数据并作为数据表返回的方法

Note- Install-Package ExcelDataReader via nuget 注意-通过nuget 安装软件包ExcelDataReader

using Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO; 
using System.Text; 

public static DataTable LoadDataTable(string filePath)
        {
            string fileExtension = Path.GetExtension(filePath);
            switch (fileExtension.ToLower())
            {
                case ".xlsx":
                    return ConvertExcelToDataTable(filePath, true);
                case ".xls":
                    return ConvertExcelToDataTable(filePath);
                case ".csv":
                    return ConvertCsvToDataTable(filePath);
                default:
                    return new DataTable();
            }

        }


public static DataTable ConvertExcelToDataTable(string filePath, bool isXlsx = false)
        {
            FileStream stream = null;
            IExcelDataReader excelReader = null;
            DataTable dataTable = null;
            stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
            excelReader = isXlsx ? ExcelReaderFactory.CreateOpenXmlReader(stream) : ExcelReaderFactory.CreateBinaryReader(stream);
            excelReader.IsFirstRowAsColumnNames = true;
            DataSet result = excelReader.AsDataSet();
            if (result != null && result.Tables.Count > 0)
                dataTable = result.Tables[0];
            return dataTable;
        }

public static DataTable ConvertCsvToDataTable(string filePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(filePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }
            return dt;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM