using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Newtonsoft.Json.Linq;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections;
using NPOI.HSSF.Util;
using System.Drawing;
/// <summary>
///ExcelHeaper 的摘要说明
/// </summary>
public class ExcelHeaper
{
public static int thisRows = 0;
public ExcelHeaper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
// using (fs = File.Copy(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
//if (filePath.IndexOf(".xls") > 0)
// workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(0);//第一行
int cellCount = firstRow.LastCellNum;//列数
//构建datatable的列
if (isColumnName)
{
startRow = 1;//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
}
//填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue;
dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.BLANK:
dataRow[j] = "";
break;
case CellType.NUMERIC:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
dataRow[j] = cell.DateCellValue;
else if (format == 20 || format == 185 || format == 184)
dataRow[j] = cell.DateCellValue.ToString("HH:mm");
else if (format == 22)
dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm");
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.FORMULA:
try
{
dataRow[j] = cell.NumericCellValue;
}
catch
{
dataRow[j] = cell.StringCellValue;
}
break;
case CellType.STRING:
dataRow[j] = cell.StringCellValue;
break;
default:
dataRow[j] = cell.CellFormula;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
return dataTable;
}
catch (Exception ex)
{
HistoryHelper.SaveError("读取Excel异常", ex.ToString());
if (fs != null)
{
fs.Close();
}
return null;
}
}
/// <summary>
/// 根据表名称将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTableByName(string filePath, bool isColumnName,string TableName)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
// using (fs = File.Copy(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
//if (filePath.IndexOf(".xls") > 0)
// workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
// sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
sheet = workbook.GetSheet(TableName);//读取固定名称的sheet;
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(0);//第一行
int cellCount = firstRow.LastCellNum;//列数
//构建datatable的列
if (isColumnName)
{
startRow = 1;//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
}
//填充行
for (int i = startRow; i <= rowCount; ++i)
{
try
{
row = sheet.GetRow(i);
if (row == null) continue;
dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.BLANK:
dataRow[j] = "";
break;
case CellType.NUMERIC:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
dataRow[j] = cell.DateCellValue;
else if (format == 20 || format == 185 || format == 184)
dataRow[j] = cell.DateCellValue.ToString("HH:mm");
else if (format == 22)
dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm");
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.FORMULA:
try
{
dataRow[j] = cell.NumericCellValue;
}
catch
{
dataRow[j] = cell.StringCellValue;
}
break;
case CellType.STRING:
dataRow[j] = cell.StringCellValue;
break;
default:
dataRow[j] = cell.CellFormula;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
catch (Exception ex)
{
HistoryHelper.SaveError("error", ex.ToString());
continue;
}
}
}
}
}
}
return dataTable;
}
catch (Exception ex)
{
HistoryHelper.SaveError("读取Excel异常", ex.ToString());
if (fs != null)
{
fs.Close();
}
return null;
}
}
/// <summary>
/// 将excel导入到datatableb并跳过前面固定行数
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTable(string filePath, bool isColumnName,int rows =0)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
// using (fs = File.Copy(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
//if (filePath.IndexOf(".xls") > 0)
// workbook = new HSSFWorkbook(fs);
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(0);//第一行
int cellCount = firstRow.LastCellNum;//列数
thisRows = rowCount;
//构建datatable的列
if (isColumnName)
{
startRow = 1;//如果第一行是列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
}
//填充行
for (int i = thisRows; i <= rowCount; i++)
{
row = sheet.GetRow(i);
if (row == null) continue;
dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.BLANK:
dataRow[j] = "";
break;
case CellType.NUMERIC:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58 || format == 186)
dataRow[j] = cell.DateCellValue;
else if (format == 20 || format == 185 || format == 184)
dataRow[j] = cell.DateCellValue.ToString("HH:mm");
else if (format == 22)
dataRow[j] = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm");
else
dataRow[j] = cell.NumericCellValue;
break;
case CellType.FORMULA:
try
{
dataRow[j] = cell.NumericCellValue;
}
catch
{
dataRow[j] = cell.StringCellValue;
}
break;
case CellType.STRING:
dataRow[j] = cell.StringCellValue;
break;
default:
dataRow[j] = cell.CellFormula;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
thisRows = rowCount;
}
}
}
}
return dataTable;
}
catch (Exception ex)
{
HistoryHelper.SaveError("读取Excel异常", ex.ToString());
if (fs != null)
{
fs.Close();
}
return null;
}
}
/// <summary>
/// 文件输出流
/// </summary>
/// <param name="bytes"></param>
public static void OutputClient(byte[] bytes)
{
HttpResponse response = HttpContext.Current.Response;
response.Buffer = true;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")));
response.Charset = "GB2312";
response.ContentEncoding = Encoding.GetEncoding("GB2312");
response.BinaryWrite(bytes);
response.Flush();
response.Close();
}
/// <summary>
/// datatable 转换为jarry
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static JArray DataTableJArray(DataTable dt)
{
JArray ja = new JArray();
foreach (DataRow row in dt.Rows)
{
JObject jo = new JObject();
foreach (DataColumn col in dt.Columns)
{
jo[col.ColumnName] = row[col.ColumnName].ToString();
}
ja.Add(jo);
}
return ja;
}
/// <summary>
/// 数据导出
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string GetCSV(JArray ja, Dictionary<string, object> StrDate)
{
HttpContext context = HttpContext.Current;
string Code = StrDate["fieldCode"].ToString();
string Name = StrDate["fieldName"].ToString();
string ExcelName = StrDate["ExcelName"].ToString();
string[] fieldCode = Code.Split(',');
string[] fieldName = Name.Split(',');
JArray jaTH = new JArray();
for (int i = 0; i < fieldCode.Length; i++)
{
JObject joTH = new JObject();
joTH["Index"] = i;
joTH["FieldCode"] = fieldCode[i];
joTH["FieldName"] = fieldName[i];
joTH["FieldDataType"] = "nvarchar";
joTH["Display"] = true;
joTH["Width"] = 100;
joTH["ForeColor"] = "#000000";
joTH["BackColor"] = "#FFFFFF";
jaTH.Add(joTH);
}
JObject queryData = new JObject();
queryData["MasterData"] = ja;
JObject tableHead = new JObject();
tableHead["TableHeader"] = jaTH;
string sheetName = ExcelName + DateTime.Now.ToString("yyyyMMddHHmmss");
MemoryStream ms = new MemoryStream();
GetExcelMemoryStream(tableHead, queryData, ms);
ms.Flush();
ms.Position = 0;
context.Response.Clear();
context.Response.Charset = "utf-8";
context.Response.Buffer = false;
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(sheetName) + ".xls");
context.Response.BinaryWrite(ms.ToArray());
context.ApplicationInstance.CompleteRequest();
context.Response.End();
ms.Close();
return string.Empty;
}
/// <summary>
/// 生成Excel写入流
/// </summary>
/// <param name="tableHead"></param>
/// <param name="queryData"></param>
/// <param name="ms"></param>
public static void GetExcelMemoryStream(JObject tableHead, JObject queryData, MemoryStream ms)
{
JArray ja = (JArray)tableHead["TableHeader"];
JArray jaTH = new JArray();
foreach (JObject jo in ja.OrderBy(f => (int)f["Index"]))
{
jaTH.Add(jo);
}
//处理把它转换成十六进制并放入一个数
//int[] color = new int[3];
//color[0] = Integer.parseInt(str.substring(1, 3), 16);
//color[1] = Integer.parseInt(str.substring(3, 5), 16);
//color[2] = Integer.parseInt(str.substring(5, 7), 16);
自定义颜色
//HSSFPalette palette = workbook.getCustomPalette();
//palette.setColorAtIndex(HSSFColor.BLACK.index, (byte)color[0], (byte)color[1], (byte)color[2]);
将自定义的颜色引入进来
//HSSFFont font = workbook.createFont();
//font.setColor(HSSFColor.BLACK.index);
//HSSFCellStyle cellStyle = workbook.createCellStyle();
//cellStyle.setFont(font);
for (int i = jaTH.Count - 1; i >= 0; i--)
{
string display = jaTH[i]["Display"].ToString().ToUpper();
if (display == "FLASE" || display == "N") jaTH.RemoveAt(i);
}
JObject joMM = (JObject)tableHead["ModuleMaster"];
JArray jaData = (JArray)queryData["MasterData"];
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet("Sheet1");
//自定义颜色
Hashtable htColor = new Hashtable();
foreach (JObject joTH in jaTH)
{
string fcStr = joTH["ForeColor"].ToString();
if (fcStr != "none" && !htColor.ContainsKey(fcStr))
{
int[] fc = new int[3];
fc[0] = Convert.ToInt32(fcStr.Substring(1, 2), 16);
fc[1] = Convert.ToInt32(fcStr.Substring(3, 2), 16);
fc[2] = Convert.ToInt32(fcStr.Substring(5, 2), 16);
short fcIndex = GetXLColour(hssfworkbook, Color.FromArgb(fc[0], fc[1], fc[2]));
htColor.Add(fcStr, fcIndex);
}
string bcStr = joTH["BackColor"].ToString();
if (bcStr != "none" && !htColor.ContainsKey(bcStr))
{
int[] bc = new int[3];
bc[0] = Convert.ToInt32(bcStr.Substring(1, 2), 16);
bc[1] = Convert.ToInt32(bcStr.Substring(3, 2), 16);
bc[2] = Convert.ToInt32(bcStr.Substring(5, 2), 16);
short bcIndex = GetXLColour(hssfworkbook, Color.FromArgb(bc[0], bc[1], bc[2]));
htColor.Add(bcStr, bcIndex);
}
}
//表头样式
ICellStyle csHead = hssfworkbook.CreateCellStyle();
csHead.WrapText = false;
csHead.VerticalAlignment = VerticalAlignment.CENTER;
csHead.Alignment = HorizontalAlignment.CENTER;
csHead.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.GREY_25_PERCENT.index;
csHead.FillPattern = FillPatternType.SOLID_FOREGROUND;
csHead.BorderBottom = BorderStyle.THIN;
csHead.BorderLeft = BorderStyle.THIN;
csHead.BorderRight = BorderStyle.THIN;
csHead.BorderTop = BorderStyle.THIN;
//表头
HSSFRow rowHead = (HSSFRow)sheet1.CreateRow(0);
for (int i = 0; i < jaTH.Count; i++)
{
bool display = (jaTH[i]["Display"].ToString() != "N");
if (!display) continue;
string fieldName = jaTH[i]["FieldName"].ToString();
int width = (int)jaTH[i]["Width"];
sheet1.SetColumnWidth(i, (fieldName.Length + 1) * 2 * 256);
ICell cell = rowHead.CreateCell(i, CellType.STRING);
cell.SetCellValue(fieldName);
cell.CellStyle = csHead;
}
//数据
ICellStyle[] cellStyle = new ICellStyle[jaTH.Count];
IFont[] font = new IFont[jaTH.Count];
for (int r = 0; r < jaData.Count; r++)
{
JObject joData = (JObject)jaData[r];
HSSFRow row = (HSSFRow)sheet1.CreateRow(r + 1);
for (int i = 0; i < jaTH.Count; i++)
{
bool display = (jaTH[i]["Display"].ToString() != "N");
if (!display) continue;
string fcStr = jaTH[i]["ForeColor"].ToString();
string bcStr = jaTH[i]["BackColor"].ToString();
bool needCreateFont = (font[i] == null);
if (needCreateFont)
{
font[i] = hssfworkbook.CreateFont();
if (fcStr != "none")
{
font[i].Color = (short)htColor[fcStr];
}
}
bool needCreateCellStyle = (cellStyle[i] == null);
if (needCreateCellStyle)
{
cellStyle[i] = hssfworkbook.CreateCellStyle();
cellStyle[i].WrapText = true;
cellStyle[i].VerticalAlignment = VerticalAlignment.CENTER;
if (bcStr != "none")
{
cellStyle[i].FillForegroundColor = (short)htColor[bcStr];
cellStyle[i].FillPattern = FillPatternType.SOLID_FOREGROUND;
}
cellStyle[i].BorderBottom = BorderStyle.THIN;
cellStyle[i].BorderLeft = BorderStyle.THIN;
cellStyle[i].BorderRight = BorderStyle.THIN;
cellStyle[i].BorderTop = BorderStyle.THIN;
cellStyle[i].SetFont(font[i]);
}
string fieldCode = jaTH[i]["FieldCode"].ToString();
string fieldDataType = jaTH[i]["FieldDataType"].ToString();
ICell cell;
if (fieldDataType.StartsWith("numeric("))
{
string[] strAry = fieldDataType.TrimStart("numeric(".ToCharArray()).TrimEnd(')').Trim().Split(',');
int precision = int.Parse(strAry[1]);
cell = row.CreateCell(i);
if (joData[fieldCode] != null) cell.SetCellValue(Convert.ToDouble(joData[fieldCode]));
if (needCreateCellStyle)
{
cellStyle[i].DataFormat = HSSFDataFormat.GetBuiltinFormat("0." + new string('0', precision));
cellStyle[i].Alignment = HorizontalAlignment.RIGHT;
}
cell.CellStyle = cellStyle[i];
}
else if (fieldDataType == "float" || fieldDataType == "double" || fieldDataType == "int" || fieldDataType == "decimal")
{
cell = row.CreateCell(i, CellType.NUMERIC);
if (joData[fieldCode] != null && joData[fieldCode].ToString() != string.Empty) cell.SetCellValue(Convert.ToDouble(joData[fieldCode]));
if (needCreateCellStyle)
{
cellStyle[i].Alignment = HorizontalAlignment.RIGHT;
}
cell.CellStyle = cellStyle[i];
}
else if (fieldDataType == "datetime")
{
cell = row.CreateCell(i);
if (joData[fieldCode] != null)
{
if (joData[fieldCode].ToString() == string.Empty)
cell.SetCellValue(string.Empty);
else
cell.SetCellValue(Convert.ToDateTime(joData[fieldCode]));
}
IDataFormat format = hssfworkbook.CreateDataFormat();
if (needCreateCellStyle)
{
cellStyle[i].DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss");
cellStyle[i].Alignment = HorizontalAlignment.CENTER;
}
cell.CellStyle = cellStyle[i];
}
else if (fieldDataType == "date")
{
cell = row.CreateCell(i);
if (joData[fieldCode] != null)
{
if (joData[fieldCode].ToString() == string.Empty)
cell.SetCellValue(string.Empty);
else
cell.SetCellValue(Convert.ToDateTime(joData[fieldCode]));
}
IDataFormat format = hssfworkbook.CreateDataFormat();
if (needCreateCellStyle)
{
cellStyle[i].DataFormat = format.GetFormat("yyyy-MM-dd");
cellStyle[i].Alignment = HorizontalAlignment.CENTER;
}
cell.CellStyle = cellStyle[i];
}
else
{
cell = row.CreateCell(i, CellType.STRING);
if (joData[fieldCode] != null) cell.SetCellValue(joData[fieldCode].ToString());
if (needCreateCellStyle)
{
cellStyle[i].Alignment = HorizontalAlignment.LEFT;
}
cell.CellStyle = cellStyle[i];
}
}
}
hssfworkbook.Write(ms);
}
/// <summary>
/// 得到Excel调色板颜色索引
/// </summary>
/// <param name="workbook"></param>
/// <param name="SystemColour"></param>
/// <returns></returns>
public static short GetXLColour(HSSFWorkbook workbook, System.Drawing.Color SystemColour)
{
short s = 0;
HSSFPalette XlPalette = workbook.GetCustomPalette();
HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
if (XlColour == null)
{
if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
{
if (false && NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
{
//NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE = 64;
//NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;
XlColour = XlPalette.AddColor(SystemColour.R, SystemColour.G, SystemColour.B);
}
else
{
XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
}
s = XlColour.GetIndex();
}
}
else
s = XlColour.GetIndex();
return s;
}
}