命名空间
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
1.导出Excel文件
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="TableName"></param>
public static void ExportDataToExcel(DataTable TableName)
{
string FileName = DateTime.Now.GetHashCode().ToString();
SaveFileDialog saveFileDialog = new SaveFileDialog
{
//设置文件标题
Title = "导出Excel文件",
//设置文件类型
Filter = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls",
//设置默认文件类型显示顺序
FilterIndex = 1,
//是否自动在文件名中添加扩展名
AddExtension = true,
//是否记忆上次打开的目录
RestoreDirectory = true,
//设置默认文件名
FileName = FileName
};
//按下确定选择的按钮
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
//获得文件路径
string localFilePath = saveFileDialog.FileName.ToString();
//数据初始化
int TotalCount; //总行数
int RowRead = 0; //已读行数
TotalCount = TableName.Rows.Count;
//NPOI
IWorkbook workbook;
string FileExt = Path.GetExtension(localFilePath).ToLower();
if (FileExt == ".xlsx")
{
workbook = new XSSFWorkbook();
}
else if (FileExt == ".xls")
{
workbook = new HSSFWorkbook();
}
else
{
workbook = null;
}
if (workbook == null)
{
return;
}
ISheet sheet = string.IsNullOrEmpty(FileName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(FileName);
//秒钟
Stopwatch timer = new Stopwatch();
timer.Start();
try
{
//读取标题
IRow rowHeader = sheet.CreateRow(0);
for (int i = 0; i < TableName.Columns.Count; i++)
{
ICell cell = rowHeader.CreateCell(i);
cell.SetCellValue(TableName.Columns[i].ColumnName);
}
//读取数据
for (int i = 0; i < TableName.Rows.Count; i++)
{
IRow rowData = sheet.CreateRow(i + 1);
for (int j = 0; j < TableName.Columns.Count; j++)
{
ICell cell = rowData.CreateCell(j);
cell.SetCellValue(TableName.Rows[i][j].ToString());
}
//状态栏显示
RowRead++;
int Percent = (int)(100 * RowRead / TotalCount);
System.Windows.Forms.Application.DoEvents();
}
System.Windows.Forms.Application.DoEvents();
//转为字节数组
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//保存为Excel文件
using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, 0, buf.Length);
fs.Flush();
fs.Close();
}
System.Windows.Forms.Application.DoEvents();
//关闭秒钟
timer.Reset();
timer.Stop();
//成功提示
if (MessageBox.Show("导出成功,是否立即打开?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
System.Diagnostics.Process.Start(localFilePath);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
//关闭秒钟
timer.Reset();
timer.Stop();
}
}
}
2.导入Excel文件到datetable
/// <summary>
/// 获取Excel到Datatable中
/// </summary>
/// <param name="filePath">Excel路径</param>
/// <returns>返回DataTable数据</returns>
public static DataTable GetExcel(string filePath)
{
IWorkbook iwkX;
using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
iwkX = WorkbookFactory.Create(fs);
fs.Close();
}
//sheet
DataTable dt = new DataTable();
for (int h = 0; h < iwkX.NumberOfSheets; h++)
{
ISheet sheet = iwkX.GetSheetAt(h);
var rows = sheet.GetRowEnumerator();
bool isMove = rows.MoveNext();
//循环sheet
if (isMove)
{
var Cols = (IRow)rows.Current;
dt.TableName = sheet.SheetName;
for (int i = 0; i < Cols.LastCellNum; i++)
{
string str = Cols.GetCell(i).ToString();
dt.Columns.Add(Cols.GetCell(i).ToString());
}
while (rows.MoveNext())
{
var row = (IRow)rows.Current;
var dr = dt.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
var cell = row.GetCell(i);
if (cell == null)
{
dr[i] = "";
}
else
{
string strdr = cell.ToString();
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
}
}
return dt;
}