[英]reading empty Rows from Excel ( *.xlsx )
當我使用以下代碼從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 = 1048574
和colCount = 17
,但在文件中, data = 9000
填充的行data = 9000
且columns = 14
如何只讀取那些內容以及代碼中的更改,因為我out of memory Exception
...
我強烈懷疑這與正在使用的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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.