NPOI导入导出
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
namespace Transport.Helper
{
public class ExcelHelper
{
/// <summary>
/// Excel导入成Datable
/// </summary>
/// <param name="file">导入路径(包含文件名与扩展名)</param>
/// <returns></returns>
public static DataTable ExcelToTable(string file)
{
DataTable dt = new DataTable();
IWorkbook workbook;
string fileExt = Path.GetExtension(file).ToLower();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
//XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
if (workbook == null) { return null; }
ISheet sheet = workbook.GetSheetAt(0);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; i < header.LastCellNum; i++)
{
object obj = GetValueType(header.GetCell(i));
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
//hasValue = false;
foreach (int j in columns)
{
if (sheet.GetRow(i) == null)
{
dr[j] = null;
//hasValue = true;
continue;
}
dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));//遇到空行,sheet.GetRow(i)不能实例化,无法调用方法,故抛异常
//if (dr[j] != null && dr[j].ToString() != string.Empty)
//{
// hasValue = true;
//}
}
//去除空行,空行不添加
//if (hasValue)
//{
dt.Rows.Add(dr);
//}
}
}
return dt;
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dt"></param>
public static void TableToExcel(DataTable dt, string[] fieldArr, Dictionary<string, string> fieldDic)
{
HSSFWorkbook wb = new HSSFWorkbook();
//标题样式样式
ICellStyle titleStyle = wb.CreateCellStyle();
IFont font1 = wb.CreateFont();//字体
font1.FontName = "楷体";
font1.Color = HSSFColor.White.Index;//字体颜色
font1.Boldweight = (short)FontBoldWeight.Normal;//字体加粗
titleStyle.SetFont(font1);//设置字体
//设置背景色
titleStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
titleStyle.FillPattern = FillPattern.SolidForeground;
titleStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Blue.Index;
titleStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;//文字水平对齐方式
titleStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//文字垂直对齐方式
//创建一个表单
ISheet sheet = wb.CreateSheet("Sheet0");
//设置列宽
int[] columnWidth = { 10, 10, 25, 10, 15, 15, 20, 10, 20, 20, 15, 15 };
for (int i = 0; i < columnWidth.Length; i++)
{
//设置列宽度,256*字符数,因为单位是1/256个字符
sheet.SetColumnWidth(i, 256 * columnWidth[i]);
}
IRow row;
ICell cell;
////写入标题行
//row = sheet.CreateRow(0);
//for (int i = 0; i < fieldArr.Length; i++)
//{
// cell = row.CreateCell(i);//创建第j列
// cell.CellStyle = titleStyle;
// SetCellValue(cell, fieldDic[fieldArr[i]]);
//}
//写入数据,从第2行开始
for (int i = 0; i <= dt.Rows.Count; i++)
{
row = sheet.CreateRow(i+1);//创建第i行
for (int j = 0; j < dt.Columns.Count; j++)
{
cell = row.CreateCell(j);
//根据数据类型设置不同类型的cell
object obj = null;
//如果报错,跳过该字段
try
{
obj = dt.Rows[i][j].ToString();
}
catch
{
continue;
}
if (obj != null)
{
SetCellValue(cell, obj);
}
}
}
//发送到客户端
MemoryStream ms = new MemoryStream();
wb.Write(ms);
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("WS" + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
wb = null;
ms.Close();
ms.Dispose();
}
/// <summary>
/// 根据数据类型设置不同类型的cell
/// </summary>
/// <param name="cell"></param>
/// <param name="obj"></param>
public static void SetCellValue(ICell cell, object obj)
{
try
{
if (obj.GetType() == typeof(int))
{
cell.SetCellValue((int)obj);
}
else if (obj.GetType() == typeof(double))
{
cell.SetCellValue((double)obj);
}
else if (obj.GetType() == typeof(IRichTextString))
{
cell.SetCellValue((IRichTextString)obj);
}
else if (obj.GetType() == typeof(string))
{
cell.SetCellValue(obj.ToString());
}
else if (obj.GetType() == typeof(DateTime))
{
cell.SetCellValue(Convert.ToDateTime(obj).ToString("yyyy/MM/dd"));
}
else if (obj.GetType() == typeof(bool))
{
cell.SetCellValue((bool)obj);
}
else
{
cell.SetCellValue(obj.ToString());
}
}
catch (Exception ex)
{
}
}
/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
}
}