ASP.NET之Excel下载模板、导入、导出操作

编辑: admin 分类: .net 发布时间: 2022-03-10 来源:互联网

本文介绍了ASP.NET下Excel下载模板、导入、导出操作,供大家参考,具体内容如下

1.下载模板功能

protected void btnDownload_Click(object sender, EventArgs e)
{
 var path = Server.MapPath(("upfiles\\") + "test.xlt"); //upfiles-文件夹 test.xlt-文件
 var name = "test.xlt";

 try
 {
 var file = new FileInfo(path);
 Response.Clear();
 Response.Charset = "GB2312";
 Response.ContentEncoding = System.Text.Encoding.UTF8;
 Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //头信息,指定默认文件名
 Response.AddHeader("Content-Length", file.Length.ToString());//显示下载进度
 Response.ContentType = "application/ms-excel"; // 指定返回的是一个不能被客户端读取的流,必须被下载
 Response.WriteFile(file.FullName); // 把文件流发送到客户端
  
 HttpContext.Current.ApplicationInstance.CompleteRequest();
 }
 catch (Exception ex)
 {
 Response.Write("<script>alert('错误:" + ex.Message + ",请尽快与管理员联系')</script>");
 }
}

2.导入数据
Excel数据导入到数据库中。 

protected void btnImport_Click(object sender, EventArgs e)
{
 if (FileUpload1.HasFile == false) //判断是否包含一个文件
 {
 Response.Write("<script>alert('请您选择Excel文件!')</script>");//未上传就点击了导入按钮
 return;
 }
 string isXls = Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//获得文件的扩展名
 var extenLen = isXls.Length;

 if (!isXls.Contains(".xls")) //判断是否 是excel文件
 {
 Response.Write("<script>alert('只可以选择Excel文件!')</script>");
 return;
 }

 string filename = FileUpload1.FileName;  //获取Excle文件名
 string savePath = Server.MapPath(("upfiles\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
 string savePath2 = Server.MapPath(("upfiles\\"));

 if (!Directory.Exists(savePath2)) //如果不存在upfiles文件夹则创建
 {
 Directory.CreateDirectory(savePath2);
 }
 FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
 var ds = ExcelSqlConnection(savePath, filename);  //将Excel转成DataSet
 var dtRows = ds.Tables[0].Rows.Count;
 var dt = ds.Tables[0];
 if (dtRows == 0)
 {
 Response.Write("<script>alert('Excel表无数据!')</script>");
 return;
 }
 try
 {
 for(int i = 0; i < dt.Rows.Count; i++)
 {
  string ve = dt.Rows[i]["车号"].ToString();
  if (string.IsNullOrEmpty(ve)) //因数据库中车号不能为空 所以表格中车号为空的跳过这行
  {
  continue;
  }
  //用自己的方式保存进数据库ADO/EF/...
  var model = new TEST(); //实体
  model.id = 1;
  model.ve = ve;
  model.name = dt.Rows[i]["姓名"].ToString();
  model.Update();
 }
 }catch (Exception ex)
 {
 Response.Write("<script>alert('" + ex.Message + "')</script>"); 
 }
 
}

private DataSet ExcelSqlConnection(string savePath, string tableName)
{
 //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
 string strCon = "Provider=Microsoft.Ace.OLEDB.12.0;" + "data source=" + savePath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //HDR=YES Excel文件的第一行是列名而不是数据 IMEX=1可必免数据类型冲突
 var excelConn = new OleDbConne【文章来源:新加坡服务 欢迎留下您的宝贵建议】ction(strCon);
 try
 {
 string strCom = string.Format("SELECT * FROM [Sheet1$]");
 excelConn.Open();
 OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, excelConn);
 DataSet ds = new DataSet();
 myCommand.Fill(ds, "[" + tableName + "$]");
 excelConn.Close();
 return ds;
 }
 catch (Exception)
 {
 excelConn.Close();
 //Response.Write("<script>alert('" + ex.Message + "')</script>");
 return null;
 }

}

3.导出数据到Excel中
插件采用MyXLS.
以下代码大部分基本不用改。 

private void Export()
{
 XlsDocument xls = new XlsDocument();
 org.in2bits.MyXls.Cell cell;
 int rowIndex = 2;

 xls.FileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + HttpUtility.UrlEncode("TEST") + ".xls"; //TEST要改
 Worksheet sheet = xls.Workbook.Worksheets.AddNamed("TEST");//状态栏标题名称
 org.in2bits.MyXls.Cells cells = sheet.Cells;

 #region 表头
 MergeArea area = new MergeArea(1, 1, 1, 2); //MergeArea(int rowMin, int rowMax, int colMin, int colMax)
 org.in2bits.MyXls.Cell cellTitle = cells.AddValueCell(1, 1, "TEST"); //Excel 第一行第1到2列显示TEST
 sheet.AddMergeArea(area);
 cellTitle.Font.Height = 20 * 20;
 cellTitle.Font.Bold = true;//设置标题行的字体为粗体
 cellTitle.Font.FontFamily = FontFamilies.Roman;//设置标题行的字体为FontFamilies.Roman
 cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;

 area = new MergeArea(2, 2, 1, 1);
 cellTitle = cells.AddValueCell(2, 1, "车号"); //第二行第一列 显示车号
 sheet.AddMergeArea(area);
 cellTitle.Font.Bold = true;
 cellTitle.Font.Height = 16 * 16;
 cellTitle.Font.FontFamily = FontFamilies.Roman;
 cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
 cellTitle.VerticalAlignment = VerticalAlignments.Centered;
 cellTitle.TopLineStyle = 1;
 cellTitle.BottomLineStyle = 1;
 cellTitle.LeftLineStyle = 1;
 cellTitle.RightLineStyle = 1;

 area = new MergeArea(2, 2, 2, 2);
 cellTitle = cells.AddValueCell(2, 2, "姓名");
 sheet.AddMergeArea(area);
 cellTitle.Font.Bold = true;
 cellTitle.Font.Height = 16 * 16;
 cellTitle.Font.FontFamily = FontFamilies.Roman;
 cellTitle.HorizontalAlignment = HorizontalAlignments.Centered;
 cellTitle.VerticalAlignment = VerticalAlignments.Centered;
 cellTitle.TopLineStyle = 1;
 cellTitle.BottomLineStyle = 1;
 cellTitle.LeftLineStyle = 1;
 cellTitle.RightLineStyle = 1;

 #endregion

 var list = GetList(); //获取数据

 for (int i = 0; i < list.Count; i++)
 {
 rowIndex++;
 cell = cells.AddValueCell(rowIndex, 1, list[i].VehicleNO); //车号
 cell.TopLineStyle = 1;
 cell.BottomLineStyle = 1;
 cell.LeftLineStyle = 1;
 cell.RightLineStyle = 1;

 cell = cells.AddValueCell(rowIndex, 2, list[i].Name); //姓名
 cell.TopLineStyle = 1;
 cell.BottomLineStyle = 1;
 cell.LeftLineStyle = 1;
 cell.RightLineStyle = 1;

 }
 xls.Send();
}

4.错误-未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序
01.将平台换成X86
02.安装 AccessDatabaseEngine.exe(点击下载) 

5.错误-服务器无法在发送HTTP标头之后设置内容类型
给导出按钮增加'全局刷新'的能力。本文例子是aspx做的在<asp:UpdatePanel> 标签中 增加如下代码即可
 复制代码 代码如下:<Triggers>
    <%--<asp:AsyncPostBackTrigger ControlID="" />--%> <%--局部刷新 值刷新UpdatePanel内部 --%>
   <asp:PostBackTrigger ControlID="btnExport" /> <%--全部刷新 --%> <%--2016年7月1日 解决点击导出按钮报错“服务器无法在发送HTTP标头之后设置内容类型”的错误--%>
</Triggers>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持海外IDC网。

更多阅读