I am reading a excel file using OLEDBConnection. I can import xls, xlsx, and xlsm. I have just a little problem with to read a merged cell. For example, i have cell A2, A3 and A4 which is merged. But in my datagridview, i have juste A2. A3 and A4 are string empty. How can i read the value of A3 and A4. Or how can i find the merged cells il the excel file.
My Code
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];
}
Thank you.