using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
/// <summary>
/// 导出数据/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtExport_Click(object sender, EventArgs e)
{
DataTable DT = new DataTable();
string localFilePath = String.Empty;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
//设置文件类型
saveFileDialog1.Filter = " xls files(*.xls)|*.txt|All files(*.*)|*.*";
//设置文件名称:
saveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + "警力数据.xls";
//设置默认文件类型显示顺序
saveFileDialog1.FilterIndex = 2;
//保存对话框是否记忆上次打开的目录
saveFileDialog1.RestoreDirectory = true;
//点了保存按钮进入
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string File = saveFileDialog1.FileName;
DT = BLL.exportMethod();
AlertBLL.SaveToExcel(DT, File);
}
}
public static void SaveToExcel(System.Data.DataTable dt, string strXLS)
{
if (dt == null || dt.Rows.Count == 0)
return;
MemoryStream ms = new MemoryStream();
IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象
ISheet mysheet = workbook.CreateSheet();//创建工作表
IRow row = mysheet.CreateRow(0);
for (int c = 0; c < dt.Columns.Count; ++c)
{
ICell cell = row.CreateCell(c);//在行中添加一列
cell.SetCellValue(dt.Columns[c].ColumnName);//设置列的内容
}
for (int r = 0; r < dt.Rows.Count; ++r)
{
row = mysheet.CreateRow(r + 1);//在工作表中添加一行
for (int c = 0; c < dt.Columns.Count; ++c)
{
ICell cell = row.CreateCell(c);//在行中添加一列
cell.SetCellValue(dt.Rows[r][c].ToString());//设置列的内容
}
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
SaveToFile(ms, strXLS);
ms.Close();
}
public static void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
data = null;
}
}