[英]reading empty Rows from Excel ( *.xlsx )
While I am reading from excel using this code: 当我使用以下代码从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;
And after the code compiled i see that the rowCount = 1048574
and colCount = 17
, but in the file the rows filled with data = 9000
and columns = 14
在编译代码后,我看到rowCount = 1048574
和colCount = 17
,但在文件中, data = 9000
填充的行data = 9000
且columns = 14
How to read those only and what the changes will be in the code because I got out of memory Exception
... 如何只读取那些内容以及代码中的更改,因为我out of memory Exception
...
I strongly suspect that this has something to do with the XLSX file being used. 我强烈怀疑这与正在使用的XLSX文件有关。 The following code, which is based on your sample with a couple of changes to which variables were being looked at, provides the expected results with a newly created Excel document: 以下代码基于您的示例,并且对要查看的变量进行了一些更改,并通过新创建的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);
}
}
}
}
With an empty document the above code will crash but does return a row count of 0. 如果文档为空,则上面的代码将崩溃,但返回的行计数为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.