ASP.NET之Excel下載模板/導(dǎo)入/導(dǎo)出操作
來源:易賢網(wǎng) 閱讀:1773 次 日期:2016-08-05 15:22:45
溫馨提示:易賢網(wǎng)小編為您整理了“ASP.NET之Excel下載模板/導(dǎo)入/導(dǎo)出操作”,方便廣大網(wǎng)友查閱!

本文介紹了ASP.NET下Excel下載模板、導(dǎo)入、導(dǎo)出操作,供大家參考,具體內(nèi)容如下

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)); //頭信息,指定默認(rèn)文件名

 Response.AddHeader("Content-Length", file.Length.ToString());//顯示下載進(jìn)度

 Response.ContentType = "application/ms-excel"; // 指定返回的是一個不能被客戶端讀取的流,必須被下載

 Response.WriteFile(file.FullName); // 把文件流發(fā)送到客戶端

 HttpContext.Current.ApplicationInstance.CompleteRequest();

 }

 catch (Exception ex)

 {

 Response.Write("<script>alert('錯誤:" + ex.Message + ",請盡快與管理員聯(lián)系')</script>");

 }

}

2.導(dǎo)入數(shù)據(jù)

Excel數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫中。 

protected void btnImport_Click(object sender, EventArgs e)

{

 if (FileUpload1.HasFile == false) //判斷是否包含一個文件

 {

 Response.Write("<script>alert('請您選擇Excel文件!')</script>");//未上傳就點擊了導(dǎo)入按鈕

 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 獲得虛擬服務(wù)器相對路徑

 string savePath2 = Server.MapPath(("upfiles\\"));

 if (!Directory.Exists(savePath2)) //如果不存在upfiles文件夾則創(chuàng)建

 {

 Directory.CreateDirectory(savePath2);

 }

 FileUpload1.SaveAs(savePath); //SaveAs 將上傳的文件內(nèi)容保存在服務(wù)器上

 var ds = ExcelSqlConnection(savePath, filename);  //將Excel轉(zhuǎn)成DataSet

 var dtRows = ds.Tables[0].Rows.Count;

 var dt = ds.Tables[0];

 if (dtRows == 0)

 {

 Response.Write("<script>alert('Excel表無數(shù)據(jù)!')</script>");

 return;

 }

 try

 {

 for(int i = 0; i < dt.Rows.Count; i++)

 {

  string ve = dt.Rows[i]["車號"].ToString();

  if (string.IsNullOrEmpty(ve)) //因數(shù)據(jù)庫中車號不能為空 所以表格中車號為空的跳過這行

  {

  continue;

  }

  //用自己的方式保存進(jìn)數(shù)據(jù)庫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文件的第一行是列名而不是數(shù)據(jù) IMEX=1可必免數(shù)據(jù)類型沖突

 var excelConn = new OleDbConnection(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.導(dǎo)出數(shù)據(jù)到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");//狀態(tài)欄標(biāo)題名稱

 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;//設(shè)置標(biāo)題行的字體為粗體

 cellTitle.Font.FontFamily = FontFamilies.Roman;//設(shè)置標(biāo)題行的字體為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(); //獲取數(shù)據(jù)

 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.錯誤-服務(wù)器無法在發(fā)送HTTP標(biāo)頭之后設(shè)置內(nèi)容類型

給導(dǎo)出按鈕增加'全局刷新'的能力。本文例子是aspx做的在<asp:UpdatePanel> 標(biāo)簽中 增加如下代碼即可

代碼如下:

<Triggers>

    <%--<asp:AsyncPostBackTrigger ControlID="" />--%> <%--局部刷新 值刷新UpdatePanel內(nèi)部 --%>

   <asp:PostBackTrigger ControlID="btnExport" /> <%--全部刷新 --%> <%--2016年7月1日 解決點擊導(dǎo)出按鈕報錯“服務(wù)器無法在發(fā)送HTTP標(biāo)頭之后設(shè)置內(nèi)容類型”的錯誤--%>

</Triggers>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助

更多信息請查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機網(wǎng)站地址:ASP.NET之Excel下載模板/導(dǎo)入/導(dǎo)出操作
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 加入群交流 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65317125(9:00—18:00) 獲取招聘考試信息及咨詢關(guān)注公眾號:hfpxwx
咨詢QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報警專用圖標(biāo)