ASP.NET之Excel下載模板、導入、導出操作


1.下載模板功能

  前提是服務器某文件夾中有這個文件。代碼如下

 1 protected void btnDownload_Click(object sender, EventArgs e)
 2 {
 3     var path = Server.MapPath(("upfiles\\") + "test.xlt");      //upfiles-文件夾 test.xlt-文件
 4     var name = "test.xlt";
 5 
 6     try
 7     {
 8         var file = new FileInfo(path);
 9         Response.Clear();
10         Response.Charset = "GB2312";
11         Response.ContentEncoding = System.Text.Encoding.UTF8;
12         Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name)); //頭信息,指定默認文件名
13         Response.AddHeader("Content-Length", file.Length.ToString());//顯示下載進度
14         Response.ContentType = "application/ms-excel";     // 指定返回的是一個不能被客戶端讀取的流,必須被下載
15         Response.WriteFile(file.FullName);    // 把文件流發送到客戶端
16             
17         HttpContext.Current.ApplicationInstance.CompleteRequest();
18     }
19     catch (Exception ex)
20     {
21         Response.Write("<script>alert('錯誤:" + ex.Message + ",請盡快與管理員聯系')</script>");
22     }
23 }

2.導入數據

  Excel數據導入到數據庫中。

 1 protected void btnImport_Click(object sender, EventArgs e)
 2 {
 3     if (FileUpload1.HasFile == false)   //判斷是否包含一個文件
 4     {
 5         Response.Write("<script>alert('請您選擇Excel文件!')</script>");//未上傳就點擊了導入按鈕
 6         return;
 7     }
 8     string isXls = Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//獲得文件的擴展名
 9     var extenLen = isXls.Length;
10 
11     if (!isXls.Contains(".xls"))    //判斷是否 是excel文件
12     {
13         Response.Write("<script>alert('只可以選擇Excel文件!')</script>");
14         return;
15     }
16 
17     string filename = FileUpload1.FileName;              //獲取Excle文件名
18     string savePath = Server.MapPath(("upfiles\\") + filename);//Server.MapPath 獲得虛擬服務器相對路徑
19     string savePath2 = Server.MapPath(("upfiles\\"));
20 
21     if (!Directory.Exists(savePath2))   //如果不存在upfiles文件夾則創建
22     {
23         Directory.CreateDirectory(savePath2);
24     }
25     FileUpload1.SaveAs(savePath);  //SaveAs 將上傳的文件內容保存在服務器上
26     var ds = ExcelSqlConnection(savePath, filename);           //將Excel轉成DataSet
27     var dtRows = ds.Tables[0].Rows.Count;
28     var dt = ds.Tables[0];
29     if (dtRows == 0)
30     {
31         Response.Write("<script>alert('Excel表無數據!')</script>");
32         return;
33     }
34     try
35     {
36         for(int i = 0; i < dt.Rows.Count; i++)
37         {
38             string ve = dt.Rows[i]["車號"].ToString();
39             if (string.IsNullOrEmpty(ve))   //因數據庫中車號不能為空 所以表格中車號為空的跳過這行
40             {
41                 continue;
42             }
43             //用自己的方式保存進數據庫ADO/EF/...
44             var model = new TEST(); //實體
45             model.id = 1;
46             model.ve = ve;
47             model.name = dt.Rows[i]["姓名"].ToString();
48             model.Update();
49         }
50     }catch (Exception ex)
51     {
52         Response.Write("<script>alert('" + ex.Message + "')</script>");   
53     }
54     
55 }
56 
57 private DataSet ExcelSqlConnection(string savePath, string tableName)
58 {
59     //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
60     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可必免數據類型沖突
61     var excelConn = new OleDbConnection(strCon);
62     try
63     {
64         string strCom = string.Format("SELECT * FROM [Sheet1$]");
65         excelConn.Open();
66         OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, excelConn);
67         DataSet ds = new DataSet();
68         myCommand.Fill(ds, "[" + tableName + "$]");
69         excelConn.Close();
70         return ds;
71     }
72     catch (Exception)
73     {
74         excelConn.Close();
75         //Response.Write("<script>alert('" + ex.Message + "')</script>");
76         return null;
77     }
78 
79 }

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 導出Excel列寬
    ColumnInfo colInfo = new ColumnInfo(xls, sheet);
    colInfo.ColumnIndexStart = 0;
    colInfo.ColumnIndexEnd = 2;     
    colInfo.Width = 15 * 300;
    sheet.AddColumnInfo(colInfo);
    #endregion

    #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> 標簽中 增加如下代碼即可

1 <Triggers>
2     <%--<asp:AsyncPostBackTrigger ControlID="" />--%> <%--局部刷新 值刷新UpdatePanel內部 --%>
3     <asp:PostBackTrigger ControlID="btnExport" /> <%--全部刷新 --%> <%--2016年7月1日 解決點擊導出按鈕報錯“服務器無法在發送HTTP標頭之后設置內容類型”的錯誤--%>
4 </Triggers>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM