asp.net針對Excel文件的導(dǎo)入與導(dǎo)出是非常常見的功能之一。本文實(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ī)范,打開時(shí)也不會有任何文件損壞之類的提示。但是在做導(dǎo)入時(shí)還是使用OleDb的方式,這種方式的導(dǎo)入在服務(wù)器端似乎還是需要裝office組件的。
一、Npoi導(dǎo)出/下載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();
}
二、Asp.Net導(dǎo)入Excel
導(dǎo)入仍然是用OleDb這種方式,感興趣的朋友可以嘗試一下其他方法。
具體功能代碼如下:
/// 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;
}
}
相信本文所述對大家的asp.net程序設(shè)計(jì)有一定的借鑒價(jià)值。
您可能感興趣的文章:- asp.net core集成CKEditor實(shí)現(xiàn)圖片上傳功能的示例代碼
- asp.net core webapi文件上傳功能的實(shí)現(xiàn)
- ASP.NET Core單文件和多文件上傳并保存到服務(wù)端的方法
- asp.net利用ashx文件實(shí)現(xiàn)文件的上傳功能
- asp.net大文件上傳解決方案實(shí)例代碼
- asp.net上傳Excel文件并讀取數(shù)據(jù)的實(shí)現(xiàn)方法
- ASP.NET Core中使用EPPlus導(dǎo)入出Excel文件的完整步驟
- ASP.NET Core 導(dǎo)入導(dǎo)出Excel xlsx 文件實(shí)例
- ASP.NET之Excel下載模板、導(dǎo)入、導(dǎo)出操作
- asp.net實(shí)現(xiàn)將Excel中多個(gè)sheet數(shù)據(jù)導(dǎo)入到SQLSERVER中的方法
- asp.net實(shí)現(xiàn)數(shù)據(jù)從DataTable導(dǎo)入到Excel文件并創(chuàng)建表的方法
- asp.net中EXCEL數(shù)據(jù)導(dǎo)入到數(shù)據(jù)庫的方法
- ASP.NET下將Excel表格中的數(shù)據(jù)規(guī)則的導(dǎo)入數(shù)據(jù)庫思路分析及實(shí)現(xiàn)
- ASP.NET 上傳文件導(dǎo)入Excel的示例