NPOI DataGridView导出EXCEL

NPOI 官方网站 http://npoi.codeplex.com/


加载NPOI.DLL
,引用这两个命名空间

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

#region NPOI DataGridView 导出 EXCEL
/// <summary>
/// NPOI DataGridView 导出 EXCEL
/// </summary>
/// <param name="fileName"> 默认保存文件名</param>
/// <param name="dgv">DataGridView</param>
/// <param name="fontname">字体名称</param>
/// <param name="fontsize">字体大小</param>
public void ExportExcel(string fileName, DataGridView dgv, string fontname, short fontsize)
{
//检测是否有数据
if (dgv.SelectedRows.Count == 0) return;
//创建主要对象
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("Weight");
//设置字体,大小,对齐方式
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].HeaderText);
dataRow.GetCell(i).CellStyle = style;
}
//注释的这行是设置筛选的
//sheet.SetAutoFilter(new CellRangeAddress(0, dgv.Columns.Count, 0, dgv.Columns.Count));
//添加列及内容
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].Cells[j].Value.GetType().ToString();
string Value = dgv.Rows[i].Cells[j].Value.ToString();
switch (ValueType)
{
case "System.String"://字符串类型
dataRow.CreateCell(j).SetCellValue(Value);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(Value, out dateV);
dataRow.CreateCell(j).SetCellValue(dateV);
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;
}
dataRow.GetCell(j).CellStyle = style;
//设置宽度
sheet.SetColumnWidth(j, (Value.Length + 10) * 256);
}
}
//保存文件
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
MemoryStream ms = new MemoryStream();
if (saveDialog.ShowDialog() == DialogResult.OK)
{
saveFileName = saveDialog.FileName;
if (!CheckFiles(saveFileName))
{
MessageBox.Show("文件被站用,请关闭文件 " + saveFileName);
workbook = null;
ms.Close();
ms.Dispose();
return;
}
workbook.Write(ms);
FileStream file = new FileStream(saveFileName, FileMode.Create);
workbook.Write(file);
file.Close();
workbook = null;
ms.Close();
ms.Dispose();
MessageBox.Show(fileName + " 保存成功", "提示", MessageBoxButtons.OK);
}
else
{
workbook = null;
ms.Close();
ms.Dispose();
}
}
#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);
/// <summary>
/// 检测文件被占用
/// </summary>
/// <param name="FileNames">要检测的文件路径</param>
/// <returns></returns>
public 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

具体效果如下:

时间: 2024-12-23 20:01:44

NPOI DataGridView导出EXCEL的相关文章

NPOI导入导出Excel

.net mvc利用NPOI导入导出excel 1.导出Excel :首先引用NPOI包,从这里下载>download(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> /// <returns></returns> public FileResult ExportStu2() { //获取list数据 var checkList = (from oc in db.Or

从DataGridView导出Excel

从DataGridView导出Excel的两种情况,不多说,直接记录代码. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Data; namespace cnblogs { public static class LoadExcel { public sta

Winform将DataGridView导出Excel,调用打印机打印DataGridView

DataGridView导出Excel (这个需要 Microsoft.Office.Interop.Excel.dll  在网上下载就可以) public static void ExportExcel(string fileName, DataGridView myDGV) { string saveFileName = ""; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = &qu

winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中

1.通过NUGET管理器下载nopi,在引入命令空间 1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.IO; 5 using NPOI.SS.UserModel; //NPOI 6 using NPOI.HSSF.Util; //NPOI 7 using NPOI.HSSF.UserModel; //NPOI 8 using NPOI.XSSF.UserModel; /

.net mvc利用NPOI导入导出excel

1.导出Excel : 首先引用NPOI包,从这里下载>download (Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> /// <returns></returns> public FileResult ExportStu2() { //获取list数据 var checkList = (from oc in db.OrganizeCustoms join o i

C#winform中datagridview导出Excel

只需要传入datagridview的name即可. 1 //导出Excel()方法 2 public void ToExcel(DataGridView dataGridView) 3 { 4 //实例化一个Excel.Application对象 5 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 6 7 if (excel == null)

&lt;转&gt;Npoi导入导出Excel操作&lt;载&gt;

1 //Datatable导出Excel 2 private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName) 3 { 4 try 5 { 6 HSSFWorkbook workbook = new HSSFWorkbook(); 7 ISheet sheet = workbook.CreateSheet("Sheet1"); 8 9 ICellStyle HeadercellStyle = wor

MVC NPOI Linq导出Excel通用类

之前写了一个模型导出Excel通用类,但是在实际应用中,可能不是直接导出模型,而是通过Linq查询后获取到最终结果再导出 通用类: public enum DataTypeEnum { Int = 0, Float = 1, Double = 2, String = 3, DateTime = 4, Date = 5 } public class ExportFieldInfo { /// <summary> /// 字段名,用于反射获取值 /// </summary> publi

Winform DataGridView导出Excel

private void 导出excelToolStripMenuItem_Click(object sender, EventArgs e) { if (dgvData.RowCount > 0) { var saveFileDialog1 = new SaveFileDialog { Filter = @"Excel文件(*.xls,*.xlsx)|*.xls;*.xlsx", RestoreDirectory = true }; if (saveFileDialog1.Sh