问题
My import works well with an .xls file, but it doesn't work with an .xlsx that I have created in Excel 2010, unless it is opened.
My code looks like this:
public static DataSet Sheets(string filePath, bool header)
{
DataSet dsResults = new DataSet();
string hasHeader = header ? "YES" : "NO";
OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder();
String strExtendedProperties = String.Empty;
sbConnection.DataSource = filePath;
if (Path.GetExtension(filePath).ToLower().Equals(".xls"))//Excel 97-03
{
sbConnection.Provider = "Microsoft.Jet.OLEDB.4.0";
strExtendedProperties = String.Format("Excel 8.0;HDR={0};IMEX=1", header);
}
else if (Path.GetExtension(filePath).ToLower().Equals(".xlsx")) // Excel 2007
{
sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0";
strExtendedProperties = String.Format("Excel 12.0;HDR={0};IMEX=1", header);
}
sbConnection.Add("Extended Properties", strExtendedProperties);
using (OleDbConnection conn = new OleDbConnection(sbConnection.ToString()))
{
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$") && !drSheet["TABLE_NAME"].ToString().EndsWith("_"))
{ .......
The error I receive on conn.Open();
I have also seen solutions saying to change things in it and save it again somehow else. Thing is I have to make it work without doing that, because it goes into a DLL that goes to other devs who will use it with a file upload on a website. So the user(client) will upload a file, and when the validation says it is a valid excel file, it will get into my code.
来源:https://stackoverflow.com/questions/14747655/external-table-is-not-in-the-expected-format-when-excel-file-is-closed