我正在使用OLEDBConnection读取excel文件。 我可以导入xls,xlsx和xlsm。 我只读了一个合并的单元格有点问题。 例如,我有合并的单元格A2,A3和A4。但在我的datagridview中,我有一个强大的A2。 A3和A4是空的字符串。 我怎样才能读取A3和A4的值。或者我如何在excel文件中找到合并的单元格。
我的代码
OpenFileDialog openFileDialog2;
openFileDialog2 = new OpenFileDialog();
// need to pass relative path after deploying on server
if (openFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
string path = openFileDialog2.FileName; //récupère le chemin absolu du fichier
/* connection string to work with excel file. HDR=Yes - indicates
that the first row contains columnnames, not data. HDR=No - indicates
the opposite. "IMEX=1;" tells the driver to always read "intermixed"
(numbers, dates, strings etc) data columns as text.
Note that this option might affect excel sheet write access negative. */
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", path);
if(path.EndsWith(".xlsm"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=\"Excel 12.0 Macro;HDR=Yes;IMEX=1\"", path);
}
else if (path.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0; data source={0}; Extended Properties=\"Excel 12.0 Xml;HDR=no;FMT=Delimited;READONLY=true\"", path);
}
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
//Get All Sheets Name
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table"});
int i = 0;
//Get the First Sheet Name
string firstSheetName = string.Empty;
for (i = 0; i < sheetsName.Rows.Count; i++)
{
if ((sheetsName.Rows[i]["TABLE_NAME"].ToString().StartsWith("'") && sheetsName.Rows[i]["TABLE_NAME"].ToString().EndsWith("'")) || path.EndsWith(".xls") || path.EndsWith(".xlsx"))
{
if (MessageBox.Show("Voulez vous chargez cette feuille ? " + Environment.NewLine + sheetsName.Rows[i]["TABLE_NAME"].ToString().Replace("$", ""), "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
{
firstSheetName = sheetsName.Rows[i]["TABLE_NAME"].ToString();
break;
}
}
}
//Query String
OleDbCommand command = new OleDbCommand("SELECT * FROM [" + firstSheetName + "]", conn);
OleDbDataAdapter ada = new OleDbDataAdapter(command);
Set = new DataSet();
ada.Fill(Set);
for (i = 0; i < 7; i++)
{
string temp = Set.Tables["table"].Rows[i][3].ToString(); //ligne 1 colonne 1
}
Set.Dispose();
dataGridView1.DataSource = Set.Tables[0];
}
谢谢。