首先寫一個NPOIHelper
/// <summary>
/// Excel生成操作類
/// </summary>
public class NPOIHelper
{
/// <summary>
/// 導出列名
/// </summary>
public static System.Collections.SortedList ListColumnsName;
/// <summary>
/// 導出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public static void ExportExcel(DataTable dtSource, string filePath)
{
if (ListColumnsName == null || ListColumnsName.Count == 0)
throw (new Exception("請對ListColumnsName設置要導出的列明!"));
HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(dtSource, excelWorkbook);
SaveExcelFile(excelWorkbook, filePath);
}
/// <summary>
/// 導出Excel
/// </summary>
/// <param name="dgv"></param>
/// <param name="filePath"></param>
public static void ExportExcel(DataTable dtSource, Stream excelStream)
{
if (ListColumnsName == null || ListColumnsName.Count == 0)
throw (new Exception("請對ListColumnsName設置要導出的列明!"));
HSSFWorkbook excelWorkbook = CreateExcelFile();
InsertRow(dtSource, excelWorkbook);
SaveExcelFile(excelWorkbook, excelStream);
}
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="excelWorkBook"></param>
/// <param name="filePath"></param>
protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, string filePath)
{
FileStream file = null;
try
{
file = new FileStream(filePath, FileMode.Create);
excelWorkBook.Write(file);
}
finally
{
if (file != null)
{
file.Close();
}
}
}
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="excelWorkBook"></param>
/// <param name="filePath"></param>
protected static void SaveExcelFile(HSSFWorkbook excelWorkBook, Stream excelStream)
{
try
{
excelWorkBook.Write(excelStream);
}
finally
{
}
}
/// <summary>
/// 創建Excel文件
/// </summary>
/// <param name="filePath"></param>
protected static HSSFWorkbook CreateExcelFile()
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
return hssfworkbook;
}
/// <summary>
/// 創建excel表頭
/// </summary>
/// <param name="dgv"></param>
/// <param name="excelSheet"></param>
protected static void CreateHeader(HSSFSheet excelSheet)
{
int cellIndex = 0;
//循環導出列
foreach (System.Collections.DictionaryEntry de in ListColumnsName)
{
HSSFRow newRow = (HSSFRow)excelSheet.CreateRow(0);
HSSFCell newCell = (HSSFCell)newRow.CreateCell(cellIndex);
newCell.SetCellValue(de.Value.ToString());
cellIndex++;
}
}
/// <summary>
/// 插入數據行
/// </summary>
protected static void InsertRow(DataTable dtSource, HSSFWorkbook excelWorkbook)
{
int rowCount = 0;
int sheetCount = 1;
HSSFSheet newsheet = null;
//循環數據源導出數據集
newsheet = (HSSFSheet)excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
foreach (DataRow dr in dtSource.Rows)
{
rowCount++;
//超出10000條數據 創建新的工作簿
if (rowCount == 10000)
{
rowCount = 1;
sheetCount++;
newsheet = (HSSFSheet)excelWorkbook.CreateSheet("Sheet" + sheetCount);
CreateHeader(newsheet);
}
HSSFRow newRow = (HSSFRow)newsheet.CreateRow(rowCount);
InsertCell(dtSource, dr, newRow, newsheet, excelWorkbook);
}
}
/// <summary>
/// 導出數據行
/// </summary>
/// <param name="dtSource"></param>
/// <param name="drSource"></param>
/// <param name="currentExcelRow"></param>
/// <param name="excelSheet"></param>
/// <param name="excelWorkBook"></param>
protected static void InsertCell(DataTable dtSource, DataRow drSource, HSSFRow currentExcelRow, HSSFSheet excelSheet, HSSFWorkbook excelWorkBook)
{
for (int cellIndex = 0; cellIndex < ListColumnsName.Count; cellIndex++)
{
//列名稱
string columnsName = ListColumnsName.GetKey(cellIndex).ToString();
HSSFCell newCell = null;
System.Type rowType = drSource[columnsName].GetType();
string drValue = drSource[columnsName].ToString().Trim();
switch (rowType.ToString())
{
case "System.String"://字符串類型
drValue = drValue.Replace("&", "&");
drValue = drValue.Replace(">", ">");
drValue = drValue.Replace("<", "<");
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期類型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(dateV);
//格式化顯示
HSSFCellStyle cellStyle = (HSSFCellStyle)excelWorkBook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)excelWorkBook.CreateDataFormat();
cellStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss");
newCell.CellStyle = cellStyle;
break;
case "System.Boolean"://布爾型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(intV.ToString());
break;
case "System.Decimal"://浮點型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值處理
newCell = (HSSFCell)currentExcelRow.CreateCell(cellIndex);
newCell.SetCellValue("");
break;
default:
throw (new Exception(rowType.ToString() + ":類型數據無法處理!"));
}
}
}
}
//排序實現接口 不進行排序 根據添加順序導出
public class NoSort : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return -1;
}
}
MVC Controller中調用
public ActionResult ExprotExcel()
{
Models.JsonResponseData jrd = new Models.JsonResponseData();
try
{
//2.爲臨時數據庫ds中創建一張表
DataTable dtSource = new DataTable("Company");
//2.1爲表創建一些列
DataColumn dc1 = new DataColumn("AutoId", typeof(int));
dc1.AllowDBNull = false;
dc1.AutoIncrement = true;
dc1.AutoIncrementSeed = 1;
dc1.AutoIncrementStep = 1;
dtSource.Columns.Add(dc1);
//增加姓名列
dtSource.Columns.Add("Company", typeof(string));
dtSource.Columns.Add("PaymentItem", typeof(string));
dtSource.Columns.Add("Amount", typeof(int));
////2.2爲表括中增加幾行數據
dtSource.Rows.Add(1, "A", "社保", 100);
dtSource.Rows.Add(2, "A", "攻擊金", 100);
dtSource.Rows.Add(3, "A", "商保", 100);
dtSource.Rows.Add(4, "A", "招用工", 100);
dtSource.Rows.Add(5, "A", "代發工資", 100);
dtSource.Rows.Add(6, "B", "社保", 220);
dtSource.Rows.Add(7, "B", "攻擊金", 210);
dtSource.Rows.Add(8, "B", "商保", 200);
dtSource.Rows.Add(9, "D", "社保", 400);
dtSource.Rows.Add(10, "D", "攻擊金", 400);
dtSource.Rows.Add(11, "D", "商保", 400);
dtSource.Rows.Add(12, "D", "代發工資", 4000);
命名空間.NPOIHelper.ListColumnsName = new SortedList(new 命名空間.NoSort());
命名空間.NPOIHelper.ListColumnsName.Add("AutoId", "編號");
命名空間.NPOIHelper.ListColumnsName.Add("Company", "公司");
命名空間.NPOIHelper.ListColumnsName.Add("PaymentItem", "產品");
命名空間.NPOIHelper.ListColumnsName.Add("Amount", "總數");
Response.Clear();
Response.BufferOutput = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
string filename = HttpUtility.UrlEncode(DateTime.Now.ToString("客服賬單"));
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.ContentType = "application/ms-excel";
命名空間.NPOIHelper.ExportExcel(dtSource, Response.OutputStream);
Response.Close();
}
catch (Exception ex)
{
jrd.Success = false;
jrd.Msg = "終止過程出錯!" + ex.Message;
}
return Json(jrd, JsonRequestBehavior.AllowGet);
}