using DevComponents.DotNetBar;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CSharpExcelHandle
{
///
/// Excel工具类
///
public static class ExcelUtils
{
///
/// Excel某sheet中内容导入到DataTable中
/// 区分xsl和xslx分别处理
///
/// Excel文件路径,含文件全名
///
public static DataTable ExcelSheetImportToDataTable(string filePath)
{
DataTable dt = new DataTable();
IWorkbook hssfworkbook;
if (Path.GetExtension(filePath).ToLower() == ".xls".ToLower())
{//.xls
#region .xls文件处理:HSSFWorkbook
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
//ISheet sheet = hssfworkbook.GetSheet(sheetName);//Excel的名称
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
//第二行最后一个方格的编号 即总的列数
for (int j = 0; j < (sheet.GetRow(1).LastCellNum); j++)
{
//设置每一列的名字
HSSFCell cell = (HSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
while (rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
if (row.RowNum == 0) continue;//第一行为标题,不需要导入
for (int i = 0; i < row.LastCellNum; i++)
{
if (i >= dt.Columns.Count)//每条记录的单元格数量不能大于表格栏位数量
{
break;
}
ICell cell = row.GetCell(i);
if ((i == 0) && (string.IsNullOrEmpty(cell.ToString()) == true))//每行第一个cell为空,break
{
break;
}
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
#endregion
}
else
{//.xlsx
#region .xlsx文件处理:XSSFWorkbook
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new XSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
//ISheet sheet = hssfworkbook.GetSheet(sheetName);//Excel的名称
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
XSSFRow headerRow = (XSSFRow)sheet.GetRow(1);
//一行最后一个方格的编号 即总的列数
for (int j = 0; j < (sheet.GetRow(1).LastCellNum); j++)
{
//设置每一列的名字
XSSFCell cell = (XSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
while (rows.MoveNext())
{
IRow row = (XSSFRow)rows.Current;
DataRow dr = dt.NewRow();
if (row.RowNum == 0) continue;//第一行标题,不需要导入
for (int i = 0; i < row.LastCellNum; i++)
{
if (i >= dt.Columns.Count) //每条记录的单元格数量不能大于表格栏位数量
{
break;
}
ICell cell = row.GetCell(i);
if ((i == 0) && (string.IsNullOrEmpty(cell.ToString()) == true))//每行第一个cell为空,break
{
break;
}
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
#endregion
}
return dt;
}
///
/// NPOI导出Excel,不依赖本地是否装有Excel,导出速度快
///
/// 要导出的dataGridView控件
/// sheet表名
///
public static void ExportToExcel(DataGridView dataGridView1, string sheetName)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = "Excel(97-2003)|*.xls";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
//不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
dataGridView1.AllowUserToAddRows = false;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow rowHead = sheet.CreateRow(0);
HSSFCellStyle hSSFCellStyle = CreateStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Left, VerticalAlignment.Center, short.MaxValue, 10, true);
//填写表头
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
rowHead.CreateCell(i, CellType.String).SetCellValue(dataGridView1.Columns[i].HeaderText.ToString());
//设置Excel单元格样式
rowHead.GetCell(i).CellStyle = hSSFCellStyle;
}
hSSFCellStyle = CreateStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Left, VerticalAlignment.Center, short.MinValue, 10, true);
ProcessFrmMgr.ProcessFrmShow(dataGridView1.Rows.Count);//显示进度条
//填写内容
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
ProcessFrmMgr.ProcessFrmAdd();//加载进度条
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
row.CreateCell(j, CellType.String).SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString());
//设置Excel单元格样式
row.GetCell(j).CellStyle = hSSFCellStyle;
}
}
ProcessFrmMgr.ProcessFrmClose();//关闭进度条
//设置单元格自适应宽度
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
int columnWidth = sheet.GetColumnWidth(j) / 256;//获取当前列宽度
for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)//在这一列上循环行
{
IRow currentRow = sheet.GetRow(rowNum);
ICell currentCell = currentRow.GetCell(j);
int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
if (columnWidth < length + 1)
{
columnWidth = length + 1;
}//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度,后面的+1是我人为的将宽度增加一个字符
}
sheet.SetColumnWidth(j, columnWidth > 255 ? 30000 : columnWidth * 256);//设置最大长度 不能超过255个字符的宽度
}
using (FileStream stream = File.OpenWrite(fileDialog.FileName))
{
workbook.Write(stream);
stream.Close();
}
MessageBoxEx.Show("导出数据成功!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
GC.Collect();
}
///
/// NPOI导出Excel,不依赖本地是否装有Excel,导出速度快
///
/// 要导出的DataTable
/// sheet表名
///
public static void ExportToExcel(DataTable dt, string sheetName)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Filter = "Excel(97-2003)|*.xls";
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
{
return;
}
//不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);
IRow rowHead = sheet.CreateRow(0);
HSSFCellStyle hSSFCellStyle = CreateStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Left, VerticalAlignment.Center, short.MaxValue, 10, true);
//填写表头
for (int i = 0; i < dt.Columns.Count; i++)
{
rowHead.CreateCell(i, CellType.String).SetCellValue(dt.Rows[0].Table.Columns[i].ToString());
//设置Excel单元格样式
rowHead.GetCell(i).CellStyle = hSSFCellStyle;
}
hSSFCellStyle = CreateStyle(workbook, NPOI.SS.UserModel.HorizontalAlignment.Left, VerticalAlignment.Center, short.MinValue, 10, true);
ProcessFrmMgr.ProcessFrmShow(dt.Rows.Count);//显示进度条
//填写内容
for (int i = 0; i < dt.Rows.Count; i++)
{
ProcessFrmMgr.ProcessFrmAdd();//加载进度条
IRow row = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
row.CreateCell(j, CellType.String).SetCellValue(dt.Rows[i][j] == null ? "" : dt.Rows[i][j].ToString());
//设置Excel单元格样式
row.GetCell(j).CellStyle = hSSFCellStyle;
}
}
ProcessFrmMgr.ProcessFrmClose();//关闭进度条
//设置单元格自适应宽度
for (int j = 0; j < dt.Columns.Count; j++)
{
int columnWidth = sheet.GetColumnWidth(j) / 256;//获取当前列宽度
for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)//在这一列上循环行
{
IRow currentRow = sheet.GetRow(rowNum);
ICell currentCell = currentRow.GetCell(j);
int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
if (columnWidth < length + 1)
{
columnWidth = length + 1;
}//若当前单元格内容宽度大于列宽,则调整列宽为当前单元格宽度,后面的+1是我人为的将宽度增加一个字符
}
sheet.SetColumnWidth(j, columnWidth > 255 ? 30000 : columnWidth * 256);//设置最大长度 不能超过255个字符的宽度
}
using (FileStream stream = File.OpenWrite(fileDialog.FileName))
{
workbook.Write(stream);
stream.Close();
}
MessageBoxEx.Show("导出数据成功!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
GC.Collect();
}
///
/// 设置样式
///
///
/// 水平布局方式
/// 垂直布局方式
/// 字体加粗 (short.MaxValue)
/// 字体大小
/// 是否需要边框 true是
///
private static HSSFCellStyle CreateStyle(HSSFWorkbook wb, NPOI.SS.UserModel.HorizontalAlignment hAlignment, VerticalAlignment vAlignment, short boldWeight, short fontPonint, bool isBorder)
{
HSSFCellStyle cellStyle = (HSSFCellStyle)wb.CreateCellStyle(); //创建列头样式
cellStyle.Alignment = hAlignment; //水平居中
cellStyle.VerticalAlignment = vAlignment; //垂直居中
if (isBorder)
{
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
}
HSSFFont cellStyleFont = (HSSFFont)wb.CreateFont(); //创建字体
cellStyleFont.Boldweight = boldWeight; //字体加粗
cellStyleFont.FontHeightInPoints = fontPonint; //字体大小
cellStyle.SetFont(cellStyleFont); //将字体绑定到样式
return cellStyle;
}
///
/// DataTable数据去重复
///
/// 数据源
/// 重复的数据
public static DataTable Distinct(DataTable dt)
{
string[] filedName = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
filedName[i] = dt.Columns[i].ColumnName;
}
DataView dv = dt.DefaultView;
DataTable DistTable = dv.ToTable("Dist", true, filedName);
return DistTable;
}
///
/// 去空行操作
///
/// DataTable
public static void DataTableRemoveEmpty(DataTable dt)
{
List removelist = new List();
for (int i = 0; i < dt.Rows.Count; i++)
{
bool IsNull = true;
for (int j = 0; j < dt.Columns.Count; j++)
{
if (!string.IsNullOrEmpty(dt.Rows[i][j].ToString().Trim()))
{
IsNull = false;
}
}
if (IsNull)
{
removelist.Add(dt.Rows[i]);
}
}
for (int i = 0; i < removelist.Count; i++)
{
dt.Rows.Remove(removelist[i]);
}
}
}
}