【发布时间】:2014-02-06 10:29:47
【问题描述】:
我有一个带有导出到 Excel 和导入 Excel 的网格视图。但是,我可以成功地从 gridview 导出数据,当我尝试导入同一个 excel 时,我无法将该 excel 导入到网格中。但是当我更改 excel 文件名并导入时,它工作正常。
谁能告诉我为什么会这样?下面是我将 excel 导入网格的代码。
protected void btnImport_Click(object sender, EventArgs e)
{
string sexcelconnectionstring = "";
string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
string path = FileUploadExcel.PostedFile.FileName;
string query = "";
Label1.Text = "";
GridView2.Visible = false;
if (strFileType != String.Empty)
{
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
}
else if (strFileType.Trim() == ".xlsx")
{
sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection conn = new OleDbConnection(sexcelconnectionstring);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = dt.Rows[0]["Table_Name"].ToString();
try
{
query = "SELECT [Size],[Order],[Ratio] FROM [" + sheetname + "]";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (objDA.IsValidExcelColumns(ds, GridView2, strSqlTable))
{
string sclearsql = "delete from " + strSqlTable;
SqlConnection sqlconn = new SqlConnection(strConnectionString);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
oledbconn.Open();
OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
OleDbDataReader dReader;
dReader = oledbcmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnectionString);
sqlBulk.DestinationTableName = strSqlTable;
sqlBulk.WriteToServer(dReader);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Data has been saved successfully.')", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please validate the excel data.')", true);
}
}
catch (Exception ex)
{
Label1.Text = "Upload status: The file could not be uploaded due to invalid column names.Please check: " + ex.Message;
}
conn.Close();
conn.Dispose();
objDA.BindGrid(GridView1, "select * from " + strSqlTable);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
}
}
这里是导出到excel的代码。
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
string strQuery = "select * from " + strSqlTable;
SqlCommand cmd = new SqlCommand(strQuery);
System.Data.DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=MyExcelData.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
【问题讨论】:
-
错误发生在哪一行,错误是什么?
-
发生在这一行 conn.Open();在 sexcel 连接字符串的正下方。错误:用户代码未处理 OleDbException。外部表不是预期的格式。
-
作为一个建议:如果您不必加载旧的 xls 文件,您可以安全地使用像 epplus 这样的库来加载文件。它速度更快,更可靠。
-
可能我必须加载 xls 文件。