ASP.Net NPOI匯入匯出
首先需要引入NPOI相應的dll,下載地址為https://download.csdn.net/download/qq_34059765/10456822
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
/// <summary>
/// 匯出excel
/// </summary>
/// <returns></returns>
public string ExportExcel2()
{
try
{
var userName = Request.QueryString["userName"];
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectString))
{
conn.Open();
using (SqlCommand command = conn.CreateCommand())
{
string sql = "select * from tb_user;";
if (!String.IsNullOrEmpty(userName))
{
sql = string.Format("select * from tb_user where userName like '%{0}%';", userName);
}
command.CommandText = sql;
using (SqlDataAdapter adp = new SqlDataAdapter(command))
{
adp.Fill(dt);
}
}
}
//設定匯出檔案路徑
string path = HttpContext.Server.MapPath("/Excel/");
string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+".xls";
//設定新建檔案路徑及名稱
string savePath = path + fileName;
IWorkbook workbook;
//XSSFWorkbook 適用XLSX格式,HSSFWorkbook 適用XLS格式
string fileExt = Path.GetExtension(fileName).ToLower();
if (fileExt == ".xlsx") {
workbook = new XSSFWorkbook();
XSSFCellStyle dateStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat format = (XSSFDataFormat)workbook.CreateDataFormat();
#region 填充樣式
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
int[] arrColWidth = new int[dt.Columns.Count];
foreach (DataColumn item in dt.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dt.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
#endregion
}
else if (fileExt == ".xls")
{
workbook = new HSSFWorkbook();
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
#region 填充樣式
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
int[] arrColWidth = new int[dt.Columns.Count];
foreach (DataColumn item in dt.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dt.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
#endregion
}
else {
workbook = null;
}
if (workbook == null)
{
return null;
}
#region 填充資料
ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);
StringBuilder strbu = new StringBuilder();
//表頭
IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
}
//資料
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
#endregion
//轉為位元組陣列
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//儲存為Excel檔案
//建立檔案
using (FileStream fs = new FileStream(savePath, FileMode.CreateNew, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
}
return savePath;
}
catch (Exception ex)
{
return null;
}
}
原始碼下載地址:https://download.csdn.net/download/qq_34059765/10456752