標籤:style blog http color os io 使用 ar for
引言
使用Npoi匯出Excel 伺服器可以不裝任何office組件,昨天在做一個匯出時用到Npoi匯出Excel,而且所導Excel也符合規範,開啟時不會有任何檔案損壞之類的提示。但是在做匯入時還是使用OleDb的方式,這種方式的匯入在伺服器端似乎還是需要裝office組件的,有沒有不需要裝組件並且能照常匯入的呢?
Npoi匯出/下載Excel
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(); }View Code
Asp.Net匯入
匯入仍然是用OleDb這種方式,有沒有其他方式搞定呢?
/// <summary> /// 串連Excel 讀取Excel資料 並返回DataSet資料集合 /// </summary> /// <param name="filepath">Excel伺服器路徑</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; } }View Code
Asp.Net 使用Npoi匯出Excel