【问题标题】:read excel data line by line with c# .net用c#.net逐行读取excel数据
【发布时间】:2013-04-23 03:56:17
【问题描述】:

有谁知道如何在 c# 中逐行读取 excel 文件。

我找到了这段代码,它将从 excel 中返​​回数据并在 c# 中显示一个grindview。但是,我只是在徘徊如何在服务器端逐行读取数据?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;    
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace site
{
    public partial class pgTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            string connString = "";
            string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
            string path = fileuploadExcel.PostedFile.FileName;
            //Connection String to Excel Workbook
            if (strFileType.Trim() == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (strFileType.Trim() == ".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            string query = "SELECT [username],[age],[phone] FROM [Sheet1$]";
            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            grvExcelData.DataSource = ds.Tables[0];
            grvExcelData.DataBind();
            da.Dispose();
            conn.Close();
            conn.Dispose();
        }    
    }
}

【问题讨论】:

  • 这段代码就可以了;只是不要将数据绑定到“grvExcelData”中(我猜这与网格视图有关)。甚至更好;你可以使用 Microsoft.Office.Interop.Excel APIs
  • 这段代码提供了你想要的数据集,不是吗?
  • 我相信他只是想检查如何逐行读取excel文件,而不是读取整个excel文件并将其值加载到网格中。

标签: c# .net


【解决方案1】:

由于 Excel 可以处理范围,因此您应该首先获取要读取的单元格范围。之后,您现在可以使用 for 循环浏览它们。您可以在下面看到一个示例:

    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\myexcel.xlsx");
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;

    int rowCount = xlRange.Rows.Count;
    int colCount = xlRange.Columns.Count;

    for (int i = 1; i <= rowCount; i++)
    {
        for (int j = 1; j <= colCount; j++)
        {
            MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
        }
    }

关于这个代码块的更详细的解释可以找到here

【讨论】:

  • Lem,您能否更新您提供的链接...它不再有效...谢谢您
  • 链接目前是 404。
【解决方案2】:

你可以使用OleDbDataReader如下

using (OleDbConnection connection = new OleDbConnection(connectionString))
{
    OleDbCommand command = new OleDbCommand(queryString, connection);

    connection.Open();
    OleDbDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        var val1= reader[0].ToString();
    }
    reader.Close();
}

【讨论】:

    【解决方案3】:

    你必须试试这个

            string connectionString = "";
            string strFileType = "Type";
            string path = @"C:\Users\UserName\Downloads\";
            string filename = "filename.xls";
            if (fielname.Contains(.xls))
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (fielname.Contains(.xlsx)
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + filename + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }
    
    
            string query = "SELECT * FROM [SheetName$]";
            using (OleDbConnection connection = new OleDbConnection(connectionString))
            {
                OleDbCommand command = new OleDbCommand(query, connection);
    
                connection.Open();
                OleDbDataReader reader = command.ExecuteReader();
    
                var lines = new List<string>();
                while (reader.Read())
                {
                    var fieldCount = reader.FieldCount;
    
                    var fieldIncrementor = 1;
                    var fields = new List<string>();
                    while (fieldCount >= fieldIncrementor)
                    {
                        fields.Add(reader[fieldIncrementor - 1].ToString());
                        fieldIncrementor++;
                    }
    
                    lines.Add(string.Join("\t", fields));
                }
                reader.Close();
            }
    

    【讨论】:

      【解决方案4】:

      我尝试了使用 OleDbConnection 的解决方案,但没有成功,因为我没有安装任何东西。然后我在这里找到了这个解决方案,它就像一个魅力:

      https://www.codeproject.com/Tips/801032/Csharp-How-To-Read-xlsx-Excel-File-With-Lines-of

      在那里您可以下载一个小文件 Excel.dll,将其添加到您的项目中,然后逐个单元格地浏览 Excel 文件。

      【讨论】:

        猜你喜欢
        • 2018-03-17
        • 2012-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-10
        • 2014-06-21
        • 2012-06-13
        相关资源
        最近更新 更多