asp.netExcel导入导出
导出:
protected void btnDC_Click(object sender, EventArgs e)
{
Response.Clear();
HttpContext.Current.Response.Charset = "gb2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment;filename=导出的文件名称.xls");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
GridView1.AllowPaging = false;
databind();//为数据控件绑定数据,在此方法中,可以定制导出数据的具体列
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
//下面重写方法一定要加上,不知道为什么
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
导入:
步骤(1)先要保存Excel文件
(2)将xls文件转成数据集
public static DataSet ExcelSqlConnection(string filepath, string tableName)
{
OleDbConnection selectConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'");
try
{
string selectCommandText = string.Format("SELECT * FROM [Sheet1$]", new object[0]);//Sheet1是xls表的名称,可以参数传递
selectConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommandText, selectConnection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
selectConnection.Close();
return dataSet;
}
catch
{
selectConnection.Close();
return null;
}
}
(3)导入
string filepath = base.Server.MapPath("/User/MB/" + this.tdSBXH.Text + ".xls");//获取上传xls文件
DataSet set = ExcelSqlConnection(filepath, this.tdSBXH.Text + ".xls");//转成数据集
DataRow[] rowArray = set.Tables[0].Select();//获得xls第一张表
for (int i = 0; i < rowArray.Length; i++)
{
string str2 = rowArray[i]["成组件编号"].ToString();//"成组件编号"为表中列名
}
异步导入用户体验更加