6

我正在使用 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];
}

谢谢你。

4

0 回答 0