Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

c# - skip first row in read of Excel file

Hello I'm trying to translate an Excel file to my dataGridView and it's having column name issues because the way the Excel file is formatted, there are two setup cells for the rest of the document. However the Column names are actually on Row #2. How can I skip the first row in the file read so that the Columns in the dataGridView show the cell values from the second row?

Current code:

  var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=Excel 8.0;", openFileDialog1.FileName);

string query = String.Format("select * from [{0}$]", "Sheet1");
var adapter = new OleDbDataAdapter(query, connectionString);

DataSet ds = new DataSet();

adapter.Fill(ds);

DataTable dt = ds.Tables[0];

techGrid.DataSource = dt;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The correct method is to tell Excel exactly where in the worksheet to find your column headers and data. Importing the entire sheet and trying to reconstruct your headers from an arbitrary data row is asking for serious trouble. OPENQUERY does not guarantee row order. In testing it will appear to always import in order, but as soon as you move it to a system with a multi-volume tempdb or a heavily loaded production system, your imports will no longer be ordered, and your code will be trying to interpret your data as column headers.

instead of:

string query = String.Format("select * from [{0}$]", "Sheet1");

use:

string query = String.Format("select * from [{0}${1}]", "Sheet1","A2:ZZ");

EDIT: use "A2:end" instead of "A2:ZZ".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...