我想上传
.xls
和
.xlsx
格式化文件。
XLSX
格式正常,但在上载时
XLS
我的错误是
外部表不是预期格式
这是我的代码,我试过了
if (fluploadData.HasFile)
{
string filename = Path.GetFileName(fluploadData.FileName);
// FileUpload.SaveAs(Server.MapPath("~/") + filename);
string filenamewithoutrext = string.Empty;
FileExt = Path.GetExtension(fluploadData.FileName).ToLower();
if (Path.GetExtension(fluploadData.FileName).ToLower() != ".xls" &&
Path.GetExtension(fluploadData.FileName).ToLower() != ".xlsx"
)
{
Response.Write("Only .xls, .xlsx are allowed.!");
return;
}
filenamewithoutrext = Path.GetFileNameWithoutExtension(fluploadData.FileName).ToLower();
string path = Server.MapPath("UploadData\\");
string filename_ = filenamewithoutrext;
// DeleteDirectory(path);
if (!Directory.Exists(path)) // CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER.
{
Directory.CreateDirectory(path);
}
else
{
foreach (string file in Directory.GetFiles(path))
{
File.Delete(file);
}
}
string fname;
fname = path + filename_ + ".xls";
fluploadData.SaveAs(fname);
HttpContext.Current.Session["ExcelFilePath"] = fname;
string conStr = "";
System.Data.DataTable dtExcelRows = new System.Data.DataTable();
switch (FileExt)
{
case ".xls": //Excel 97-03
conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = System.Configuration.ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, fname, "YES");
System.Data.OleDb.OleDbConnection connExcel = new System.Data.OleDb.OleDbConnection(conStr);
System.Data.OleDb.OleDbCommand cmdExcel = new System.Data.OleDb.OleDbCommand();
System.Data.OleDb.OleDbDataAdapter oda = new System.Data.OleDb.OleDbDataAdapter();
cmdExcel.Connection = connExcel;
connExcel.Open(); // here is coming the error
System.Data.DataTable dtExcelSchema = connExcel.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
System.Data.DataTable dtExcelColumnsTable = connExcel.GetSchema("Columns");
//string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString().Replace('\'', ' ').Trim();
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString().Replace('\'', ' ').Trim(); // nadeem
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dtExcelRows);
connExcel.Close();
bool Structure_FLG = false;
}
连接字符串也在web.config中正确设置,如下所示
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1}'"/>
我哪里做错了?