如何从Excel中的单元格中选择值

时间:2014-02-12 19:04:50

标签: c# excel merge command cells

如何在Excel中从单元格中正确选择值?我知道我的问题是选择单元格的命令。

我的实际脚本:

List<string> wsList = new List<string>();
DataTable schemaTable;
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name;
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
    _ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
    _ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}

OleDbConnection con = new OleDbConnection(_ConnectionString);

try
{
    con.Open();
    // Get schematable name from excel file
    schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    foreach (DataRow row in schemaTable.Rows)
        wsList.Add(row.Field<string>("TABLE_NAME"));
    name = wsList[0];
    // Select values from cell in excel
    string strCmd = "SELECT J38 FROM [" + name + "]"; // I think that here is my main problem
    // Command for select value
    OleDbCommand cmd = new OleDbCommand(strCmd, con);

    da.Clear();
    adapter.SelectCommand = cmd;
    adapter.Fill(da);
    UniqueValue.money.Add(double.Parse(da.ToString()));
}

catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

finally
{
    con.Close();
}

您可以观看我需要的图片选择:(合并单元格)

调试:

找不到一个或多个必需参数,没有值

1 个答案:

答案 0 :(得分:0)

合并的单元格和数据适配器不会混合。如果这是一次性的,请将原始工作表中的值复制到空工作簿中并取消合并单元格,手动执行任何其他清理。如果这是一个需要重复的生产过程,并且是高容量的,请考虑在工作簿中编写VBA宏来为您执行copypasta / cleanup过程。