asp.net針對(duì)Excel文件的導(dǎo)入與導(dǎo)出是非常常見(jiàn)的功能之一。本文實(shí)例講述了Asp.Net使用Npoi導(dǎo)入導(dǎo)出Excel的方法。分享給大家供大家參考之用。具體方法如下:
在使用Npoi導(dǎo)出Excel的時(shí)候,服務(wù)器可以不裝任何office組件,一般在導(dǎo)出時(shí)用到Npoi導(dǎo)出Excel文件,所導(dǎo)Excel也符合規(guī)范,打開(kāi)時(shí)也不會(huì)有任何文件損壞之類的提示。但是在做導(dǎo)入時(shí)還是使用OleDb的方式,這種方式的導(dǎo)入在服務(wù)器端似乎還是需要裝office組件的。
一、Npoi導(dǎo)出/下載Excel
具體功能代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public void NpoiExcel(DataTable dt, string title) { NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet sheet = book.CreateSheet( "Sheet1" ); NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0); ICellStyle style = book.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; style.VerticalAlignment = VerticalAlignment.Center; for ( int i = 0; i < dt.Columns.Count; i++) { ICell cell = headerrow.CreateCell(i); cell.CellStyle = style; cell.SetCellValue(dt.Columns[i].ColumnName); } MemoryStream ms = new MemoryStream(); book.Write(ms); Response.AddHeader( "Content-Disposition" , string .Format( "attachment; filename={0}.xls" , HttpUtility.UrlEncode(title + "_" + DateTime.Now.ToString( "yyyy-MM-dd" ), System.Text.Encoding.UTF8))); Response.BinaryWrite(ms.ToArray()); Response.End(); book = null ; ms.Close(); ms.Dispose(); } |
二、Asp.Net導(dǎo)入Excel
導(dǎo)入仍然是用OleDb這種方式,感興趣的朋友可以嘗試一下其他方法。
具體功能代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
/// <summary> /// 連接Excel 讀取Excel數(shù)據(jù) 并返回DataSet數(shù)據(jù)集合 /// </summary> /// <param name="filepath">Excel服務(wù)器路徑</param> /// <param name="tableName">Excel表名稱</param> /// <returns></returns> public static System.Data.DataSet ExcelSqlConnection( string filepath, string tableName) { string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'" ; OleDbConnection 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 { ExcelConn.Close(); return null ; } } |
相信本文所述對(duì)大家的asp.net程序設(shè)計(jì)有一定的借鑒價(jià)值。