我有一个将Excel电子表格导入数据网格视图的程序。我编写的代码如下:
try
{
OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = file;
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
data = new DataSet();
adapter.Fill(data);
dataGridView1.DataSource = data.Tables[0].DefaultView;
}
catch (IOException)
{
}
Line“selectCommand.CommandText =”SELECT * FROM [All Carpets to Excel $]“;”从该表中获取具有该名称的数据。我想知道如何让这个程序打开任何工作表名称的Excel文档。一个我可能不知道的。
提前致谢!
答案 0 :(得分:2)
您可以像这样获得所有工作表的名称..
public string[] GetExcelSheetNames(string excelFileName)
{
OleDbConnection con = null;
DataTable dt = null;
String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
con= new OleDbConnection(conStr);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}