using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.Win32;
using System.Windows;
using System.Runtime.InteropServices;
using System.Data.OleDb;
namespace SuperMap.RealEstate.ExchangeData.Common
{
public class ExcelExport
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
//workbook.Write(fs); //写入到excel,但这种直接写路径不是 下载那个位置,是虚拟目录上
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + "年度利率表.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff")));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
HttpContext.Current.Response.End();
workbook = null;
ms.Close();
ms.Dispose();
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
public int DataTableToExcel(string FileName, DataTable data, string sheetName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
if (fileName == null)
{
workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
}
else
{
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
}
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
workbook.Write(ms);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + FileName + ".qrdata"));
HttpContext.Current.Response.BinaryWrite(ms.ToArray());
HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
//HttpContext.Current.Response.End();
workbook = null;
ms.Close();
ms.Dispose();
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//if (fileName.IndexOf(".xlsx") > 0) // 2007版本
// workbook = new XSSFWorkbook(fs);
//else if (fileName.IndexOf(".xls") > 0) // 2003版本
// workbook = new HSSFWorkbook(fs);
try
{
workbook = new XSSFWorkbook(fs);
}
catch
{
workbook = new HSSFWorkbook(fs);
}
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
public DataTable ExcelToDataTable(int sheetIndex, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
//if (fileName.IndexOf(".xlsx") > 0) // 2007版本
// workbook = new XSSFWorkbook(fs);
//else if (fileName.IndexOf(".xls") > 0) // 2003版本
// workbook = new HSSFWorkbook(fs);
try
{
workbook = new XSSFWorkbook(fs);
}
catch
{
workbook = new HSSFWorkbook(fs);
}
sheet = workbook.GetSheetAt(sheetIndex);
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
}
//最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
}
return data;
}
catch (Exception ex)
{
throw ex;
}
}
#region NPOI DataGridView 导出 EXCEL
///
/// NPOI DataGridView 导出 EXCEL
///
/// 默认保存文件名
/// DataGridView
/// 字体名称
/// 字体大小
public static void ExportExcel(string fileName, string SheetName, string fontname = "宋体", short fontsize = 10, params DataTable[] arraydgv)
{
int g = 0;
HSSFWorkbook workbook = new HSSFWorkbook();
foreach (DataTable dgv in arraydgv)
{
g++;
//检测是否有数据
//if (dgv.Rows.Count == 0)
// continue;
//创建主要对象
HSSFSheet sheet = null;
//if (g == 1)
//{
sheet = (HSSFSheet)workbook.CreateSheet("Sheet"+g);
//}
//if (g == 2)
//{
// sheet = (HSSFSheet)workbook.CreateSheet("OrderControl".ToString());
//}
//设置字体,大小,对齐方式
HSSFCellStyle style = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontName = fontname;
font.FontHeightInPoints = fontsize;
style.SetFont(font);
style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //居中对齐
//添加表头
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0);
for (int i = 0; i < dgv.Columns.Count; i++)
{
dataRow.CreateCell(i).SetCellValue(dgv.Columns[i].ColumnName);
dataRow.GetCell(i).CellStyle = style;
}
//添加列及内容
for (int i = 0; i < dgv.Rows.Count; i++)
{
dataRow = (HSSFRow)sheet.CreateRow(i + 1);
for (int j = 0; j < dgv.Columns.Count; j++)
{
string ValueType = dgv.Rows[i][j].GetType().ToString();
string Value = dgv.Rows[i][j].ToString();
#region
switch (ValueType)
{
case "System.DateTime"://日期类型
//System.DateTime dateV;
//System.DateTime.TryParse(Value, out dateV);
//dataRow.CreateCell(j).SetCellValue(dateV);
////break;
case "System.String"://字符串类型
dataRow.CreateCell(j).SetCellValue(Value);
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(Value, out boolV);
dataRow.CreateCell(j).SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(Value, out intV);
dataRow.CreateCell(j).SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(Value, out doubV);
dataRow.CreateCell(j).SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
dataRow.CreateCell(j).SetCellValue("");
break;
default:
dataRow.CreateCell(j).SetCellValue("");
break;
#endregion
}
dataRow.GetCell(j).CellStyle = style;
//设置宽度
sheet.SetColumnWidth(j, (Value.Length + 10) * 256);
}
}
}
//保存文件
string saveFileName = fileName;
FileStream file = new FileStream(saveFileName.Replace(".xls", ".qrdata"), FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
}
#endregion
#region 检测文件被占用
[DllImport("kernel32.dll")]
public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
public static extern bool CloseHandle(IntPtr hObject);
public const int OF_READWRITE = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
///
/// 检测文件被占用
///
/// 要检测的文件路径
///
public static bool CheckFiles(string FileNames)
{
if (!File.Exists(FileNames))
{
//文件不存在
return true;
}
IntPtr vHandle = _lopen(FileNames, OF_READWRITE | OF_SHARE_DENY_NONE);
//if (vHandle == HFILE_ERROR)
//{
// //文件被占用
// return false;
//}
//文件没被占用
CloseHandle(vHandle);
return true;
}
#endregion
public DataTable DataEncryption(DataTable dt)
{
DataTable CloneData = new DataTable();
foreach (DataColumn dc in dt.Columns)
{
CloneData.Columns.Add(dc.ColumnName.ToEncrypt(), typeof(string));
}
for (int i = 0; i < dt.Rows.Count; i++)
{
CloneData.Rows.Add();
for (int j = 0; j < dt.Columns.Count; j++)
{
if (CloneData.Columns[j].ColumnName.ToDecrypt() != "PROWERRIGHT")
{
CloneData.Rows[i][j] = dt.Rows[i][j].ToEncrypt();
}
else
{
CloneData.Rows[i][j] = dt.Rows[i][j];
}
}
}
return CloneData;
}
public int GetExcelSheetNames(string excelFile)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + excelFile + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
if (dt == null)
{
return 0;
}
String[] excelSheets = new String[dt.Rows.Count];
int sheetsCounter = dt.Rows.Count;
return sheetsCounter;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 0;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
}
}