从Excel中读取空行(* .xlsx)

时间:2015-02-03 08:51:11

标签: c# windows excel datagridview visual-studio-2013

当我使用此代码从excel阅读时:

OpenFileDialog ofd= new OpenFileDialog();
ofd.Title = "Select file";
ofd.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
ofd.FilterIndex = 1;
ofd.RestoreDirectory = true;

if (ofImport.ShowDialog() == DialogResult.OK)
{
    string path = System.IO.Path.GetFullPath(ofImport.FileName);
    string query = "SELECT * FROM [Sheet6$]";
    OleDbConnection conn = new OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ofd.FileName + ";Extended Properties=" + "\"Excel 12.0 Xml;HDR=YES;IMEX=1\"";
    OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
    var ds= new DataSet();
    adapter.Fill(ds);
    DataTable data = dsz.Tables[0];
    datagridview1.DataSource = data
    // to get row count
    int rowCount = dg_Un_TIA.Rows.Count;
    // Get the no. of columns in the first row.
    int colCount = dg_Un_TIA.Rows[0].Cells.Count;

编译代码后,我看到rowCount = 1048574colCount = 17,但文件中的行包含data = 9000columns = 14

如何仅读取这些内容以及代码中的更改内容 因为我得到了out of memory Exception ...

1 个答案:

答案 0 :(得分:0)

我强烈怀疑这与正在使用的XLSX文件有关。以下代码基于您的示例,并对正在查看的变量进行了一些更改,使用新创建的Excel文档提供了预期结果:

using System;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Windows.Forms;

namespace TestApplication
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            OpenFileDialog ofd = new OpenFileDialog
            {
                Title = "Select file",
                Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*",
                FilterIndex = 1,
                RestoreDirectory = true
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string query = "SELECT * FROM [Sheet1$]";
                OleDbConnection conn = new OleDbConnection
                {
                    ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ofd.FileName +
                                       ";Extended Properties=" + "\"Excel 12.0 Xml;HDR=YES;IMEX=1\""
                };
                OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);

                var ds = new DataSet();
                adapter.Fill(ds);
                DataTable data = ds.Tables[0];

                var message = string.Format("Row Count: {0}{1}Column Count: {2}", data.Rows.Count, Environment.NewLine, data.Rows[0].ItemArray.Count());
                MessageBox.Show(message);
            }
        }
    }
}

对于空文档,上面的代码会崩溃,但会返回行数0.