我有.aspx页面,其中包含GridView
和asp.net按钮,用于将GridView
导出到Excel。一切正常。就是当我将GridView
导出到Excel
(。xls)时,所有行都会被导出。
Excel
文件包含产品价格。这些价格由用户Updated
提供,稍后在Uploaded
到GridView
,因此产品的价格会更新到数据库。
当我尝试将Exported Excel(.xls)
上传到GridView
时,它表示' 错误:外部表格不是预期的格式'。但是当使用选项' SAVE AS'保存相同的文件时它工作正常。
有什么建议吗?
将GridView导出到Excel(.xls)
protected void btnExportEdit_Click(object sender, EventArgs e)
{
GridView2.AllowPaging = false;
GridView2.AllowSorting = false;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=TeraPeakDevicePrices_Edit.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
//Response.ContentType = "application/text";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView2.DataSourceID = sqlUsers.ID;//sqlDevicePriceListExport.ID;
GridView2.DataBind();
StringWriter sWriter = new StringWriter();
HtmlTextWriter hWriter = new HtmlTextWriter(sWriter); GridView2.RenderControl(hWriter);
string style = @"<style> .textmode {mso-number-format:General} </style>";
Response.Write(style);
Response.Write(sWriter.ToString());
Response.Flush(); Response.End();
}
将导出的Excel(.xls)上传到GridView。
using System.Data.OleDb;
protected void btnUploadOLD_Click(object sender, EventArgs e)
{
if (fupCSV.HasFile)
{
try
{
OleDbConnection objConn = null;
string fileSavePath = "";
fileSavePath = CommonFunc.GetFileName(Path.Combine(Server.MapPath("~/" + "UploadedFiles"), fupCSV.FileName));
fupCSV.SaveAs(fileSavePath);
hdnFileUploaded.Value = fileSavePath;
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", fileSavePath);
objConn = new OleDbConnection(connectionString);
objConn.Open();
DataTable columndt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[columndt.Rows.Count];
if (columndt.Rows.Count > 0)
{
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in columndt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
}
// var adapter = new OleDbDataAdapter("SELECT * FROM [" + excelSheets[0] + "] where [Sales Record Number] is not null", connectionString);
//SMS:
var adapter = new OleDbDataAdapter("SELECT * FROM [" + excelSheets[0] + "] ", connectionString);
var ds = new DataSet();
objConn.Close();
adapter.Fill(ds, "anyNameHere");
DataTable data = ds.Tables["anyNameHere"];
if (data != null && data.Rows.Count > 0)
{
btnUpdateChanges.Visible = true;
}
else {
btnUpdateChanges.Visible = false;
}
gvExcelFile.DataSource = data.DefaultView.ToTable();
gvExcelFile.DataBind();
}
catch (Exception ex)
{
}
}
}
帮助感谢!