如何从Excel表格中获取列,如果Excel表格名称包含空格字符,即“个人详细信息”
本文关键字:表格 Excel 空格 字符 详细信息 包含 获取 如果 | 更新日期: 2023-09-27 18:03:45
这里我使用ADO。Net连接到Excel文件使用指定的connectionString工作良好,我唯一关心的是,如果表名有空格字符比它不返回列名形式相应的表。我的代码:
if (extension == ".xls")
{
connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("~''ExcelUpload''Excelsheets''temp.xls") + ";" +
@"Extended Properties=" + "'"Excel 8.0;HDR=YES;'"";
}
else if (extension == ".xlsx")
{
connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + Server.MapPath("~''ExcelUpload''Excelsheets''temp.xlsx") + ";" +
@"Extended Properties=" + "'"Excel 12.0;HDR=YES;'"";
}
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
connection.Open();
DataTable dt;
String[] restrection = { null, null, sheetName + "$", null };
dt = connection.GetSchema("Columns", restrection);
那么我们怎么能paas excel表格名称有空格字符?
也许你可以这样写:
var dataset = new DataSet();
var connectionString = "connstring";
var connection = new OleDbConnection(connectionString);
connection.Open();
var sheets = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
if (sheets == null || sheets.Rows.Count < 1) throw new InvalidOperationException("CantReadWorksheets");
foreach (DataRow sheet in sheets.Rows)
{
var tableName = sheet["Table_Name"].ToString();
var sql = "SELECT * FROM [" + tableName + "]";
var adap = new OleDbDataAdapter(sql, connection);
adap.Fill(dataset, tableName);
}
connection.Close();
你可以看到我是如何得到表名的。(try..catch
块被剪切)
Try
String[] restrictions = { null, null, "['" + sheetName + "$']", null };
如果你有一个工作表TEST工作表它就变成了TEST工作表$'
我不明白为什么我们必须遵循这样的WIERD命名约定
对于文件名中包含空格应该没有问题。在读取文件之前尝试检查文件是否存在:
System.IO.File.Exists(Server.MapPath("~''ExcelUpload''Excelsheets''temp filename.xlsx"))
代码…
String[] restrection = { null, null, sheetName + "$", null };
…在工作表名称后追加'$'。也许工作表名称需要分隔,也许…
String[] restrection = { null, null, "[" + sheetName + "]$", null };
…或…
String[] restrection = { null, null, "'"" + sheetName + "'"$", null };
……?
尝试替换:
connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("~''ExcelUpload''Excelsheets''temp.xls") + ";" +
@"Extended Properties=" + "'"Excel 8.0;HDR=YES;'"";
与这个:string conn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path +
";Extended Properties=''Excel 8.0; HDR=YES; IMEX=1;''";
与Excel 12.0相同。在我的情况下,解决这个问题:)