采用的是以DataGridView的形式导出,使用NPOI.dll

1.由于使用的是DataGridView,所以类需要创建在From的Project下,DLL导入NPOI

2.代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPOI.SS.UserModel; //NPOI
using NPOI.HSSF.Util; //NPOI
using NPOI.HSSF.UserModel; //NPOI
using NPOI.XSSF.UserModel; //NPOI
using System.IO;
namespace ESMT
{
public class ExportExcel
{
/// <summary>
///
/// </summary>
/// <param name="grdview">数据表</param>
/// <param name="sheetName">工作簿名字</param>
/// <param name="FilePath">文件路径</param>
/// <param name="columnTitle">列头</param>
public void ExportToExcel(DataGridView grdview, string sheetName, string FilePath, string[] columnTitle)
{ //不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
grdview.AllowUserToAddRows = false;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);//创建工作簿
//设置表头
IRow headerRow = sheet.CreateRow();//创建第一行
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue("出库表单");//单元格赋值
ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//格式居中
IFont font = workbook.CreateFont();
font.Boldweight = ;
font.FontHeightInPoints = ;
headStyle.SetFont(font);
headerRow.GetCell().CellStyle = headStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , grdview.ColumnCount - ));//单元格合并 最后个参数是合并个数 IRow headerRow2 = sheet.CreateRow();//创建第二行列头
ICellStyle headStyle2 = workbook.CreateCellStyle();
headStyle2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont font2 = workbook.CreateFont();
font2.FontHeightInPoints = ;
font2.Boldweight = ;
headStyle2.SetFont(font2);
for (int l = ; l < grdview.ColumnCount - ; l++) //列头填值
{
headerRow2.CreateCell(l).SetCellValue(columnTitle[l]);
headerRow2.GetCell(l).CellStyle = headStyle2;
} //设置列宽
for (int l = ; l < grdview.Columns.Count; l++)
{
sheet.DefaultColumnWidth = ;
} //填写内容
for (int i = ; i < grdview.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
for (int j = ; j < grdview.Columns.Count; j++)
{
row.CreateCell(j - , CellType.String).SetCellValue(grdview.Rows[i].Cells[j].Value.ToString());//j-1表示哪个单元格
}
} using (FileStream stream = File.OpenWrite(FilePath))//创建Excel并写入数据
{
workbook.Write(stream);
stream.Close();
}
GC.Collect();
}
}
}

ExportExcel

PS:openwtrie 打开或者创建新的文件写入

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NPOI.SS.UserModel; //NPOI
using NPOI.HSSF.Util; //NPOI
using NPOI.HSSF.UserModel; //NPOI
using NPOI.XSSF.UserModel; //NPOI
using System.IO;
namespace ESMT
{
public class ExportExcel
{
/// <summary>
/// ExportToExcel
/// </summary>
/// <param name="grdview">数据表</param>
/// <param name="sheetName">工作簿名字</param>
/// <param name="FilePath">文件路径</param>
/// <param name="columnTitle">列头</param>
public bool ExportToExcel(DataGridView grdview, string sheetName, string FilePath, string[] columnTitle, bool ischeckbox)
{
try
{
//不允许dataGridView显示添加行,负责导出时会报最后一行未实例化错误
grdview.AllowUserToAddRows = false;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(sheetName);//创建工作簿 //设置表头
IRow headerRow = sheet.CreateRow();//创建第一行
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue("出库表单");//单元格赋值 ICellStyle headStyle = workbook.CreateCellStyle();//
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//格式居中
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//格式居中 IFont font = workbook.CreateFont();
font.Boldweight = ;
font.FontHeightInPoints = ;
headStyle.SetFont(font);//设置了第一行样式的字体 headerRow.GetCell().CellStyle = headStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(, , , grdview.ColumnCount - ));//单元格合并 最后个参数是合并个数 IRow headerRow2 = sheet.CreateRow();//创建第二行列头
ICellStyle headStyle2 = workbook.CreateCellStyle();//设置第二行的样式
headStyle2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont font2 = workbook.CreateFont();
font2.FontHeightInPoints = ;
font2.Boldweight = ;
headStyle2.SetFont(font2); ICellStyle headStyle3 = workbook.CreateCellStyle();//内容的样式
headStyle3.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//格式居中
headStyle3.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;//格式居中 for (int l = ; l < grdview.ColumnCount - ; l++) //列头填值
{
headerRow2.CreateCell(l).SetCellValue(columnTitle[l]);
headerRow2.GetCell(l).CellStyle = headStyle2;
}
//设置默认列宽
//sheet.DefaultColumnWidth = 15; //设置列宽
AutoColumnWidth(sheet, grdview.ColumnCount); //填写内容
for (int i = ; i < grdview.Rows.Count; i++)
{
IRow row = sheet.CreateRow(i + );
for (int j = ; j < grdview.Columns.Count; j++)
{
if (ischeckbox)
{//带checkbox的DataGrid
row.CreateCell(j - , CellType.String).SetCellValue(grdview.Rows[i].Cells[j].Value.ToString());
row.GetCell(j - ).CellStyle = headStyle3;
}//j-1表示哪个单元格
else
{
row.CreateCell(j - , CellType.String).SetCellValue(grdview.Rows[i].Cells[j - ].Value.ToString());//j-1表示哪个单元格
row.GetCell(j - ).CellStyle = headStyle3;
}
}
} using (FileStream stream = File.OpenWrite(FilePath))//创建Excel并写入数据
{
workbook.Write(stream);
stream.Close();
}
GC.Collect();
return true;//导出成功
}
catch (Exception)
{ return false;//导出失败
}
}
/// <summary>
/// 自适应列宽
/// </summary>
/// <param name="sheet"></param>
/// <param name="cols"></param>
public void AutoColumnWidth(ISheet sheet, int cols)
{
for (int col = ; col < cols - ; col++)//个数和列头个数统一
{
sheet.AutoSizeColumn(col);//自适应宽度,但是其实还是比实际文本要宽
int columnWidth = sheet.GetColumnWidth(col) / ;//获取当前列宽度
for (int rowIndex = ; rowIndex <= sheet.LastRowNum; rowIndex++)
{
IRow row = sheet.GetRow(rowIndex);
ICell cell = row.GetCell(col);
int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度
columnWidth = columnWidth < contextLength ? contextLength : columnWidth; }
sheet.SetColumnWidth(col, columnWidth * );//设置列宽 }
}
} }

改善版1.0

3.From窗口点击导出按钮

 string[] columnTitle = { "序号", "仓位", "Facility", "供应商料号", "料号", "料卷ID", "料卷数量", "储位号", "Date Code/Lot", "生产日期", "供应商编码", "入仓时间" };
string localFilePath = "";// fileNameExt, newFileName, FilePath;
SaveFileDialog sfd = new SaveFileDialog();//保存文件窗口
//设置文件类型
sfd.Filter = "Excel(97-2003)|*.xls";//保存类型为EXCEL
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true; //点了保存按钮进入
if (sfd.ShowDialog() == DialogResult.OK)
{
localFilePath = sfd.FileName.ToString(); //获得文件路径
ex.ExportToExcel(grdData, "出库表单", localFilePath, columnTitle);
}

导出按钮

通过以上三步,完成点击导出按钮,后选择保存位置并命名,调用EportExcel方法完成导出Excel。

PS:使用DataTable的操作是一样,只是赋值的时候取DataTable的值。GC 是自动垃圾收集  如果没有Checkbox的时候可以加入一个判断标记为 传参的时候加入,根据标记为来改变赋值情况。

C#WinFrom导出Excel的更多相关文章

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

    1.通过NUGET管理器下载nopi,在引入命令空间 using System; using System.Collections.Generic; using System.Text; using ...

  2. Mvc 拼接Html 导出 Excel(服务器不用安装呦!支持2007以上版本)

    新公司,新接触,老方法,更实用. 之前接触过Webform,winfrom 的导出Excel方法 ,优点:省事.缺点:服务器必须安装Office 这几天做项目 和 大牛学习了一下 新的方法,自己加以总 ...

  3. asp.net 导出excel文件

    之前做过winfrom程序的导出excel文件的功能,感觉非常简单.现在试着做asp.net中导出excel的功能,之前用的是Microsoft.Office.Interop.Excel这个对象来实现 ...

  4. Mvc 导出 Excel

    Mvc 导出 Excel 之前接触过Webform,winfrom 的导出Excel方法 ,优点:省事.缺点:服务器必须安装Office 这几天做项目 和 大牛学习了一下 新的方法,自己加以总结.希望 ...

  5. C#使用Aspose.Cells导出Excel简单实现

    首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...

  6. 利用poi导出Excel

    import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...

  7. [django]数据导出excel升级强化版(很强大!)

    不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...

  8. NPOI导出Excel

    using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...

  9. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

随机推荐

  1. IDEA常用智能提示

    psvm: 生成代码: public static void main(String[] args) { }

  2. Android的工程目录主要有哪些

    src 源文件gen 生成的文件 R 文件就在此android. jar 依赖的 android sdkassets 资源文件bin 生成的字节码 apk 在此libs 依赖 jar 和 sores ...

  3. Libvirt Live Migration 与 Pre-Copy 实现原理

    目录 文章目录 目录 Libvirt 的 Live Migration 网络数据传输层 控制层 通过 libvirt 库实现虚拟机迁移的示例 KVM 的预拷贝(Pre-Copy)Live Migrat ...

  4. Android 调用相机、相册功能

    清单文件中增加对应权限,动态申请权限(此部分请参考Android 动态申请权限,在此不作为重点描述) private static final int REQUEST_CODE_ALBUM = 100 ...

  5. python文档的数据读取,把读取数据写入到新的表里

    目的:接口自动化过程需要从表格文件读取,然后把结果写到表格中.没有多余内容全部是精华! 读取文件1 读取文件2 代码如下图: # -*-coding:utf-8 -*-# Author:wangjun ...

  6. C#学习笔记三(委托·lambda表达式和事件,字符串和正则表达式,集合,特殊的集合)

    委托和事件的区别 序号 区别 委托 事件 1 是否可以使用=来赋值 是 否 2 是否可以在类外部进行调用 是 否 3 是否是一个类型 是 否,事件修饰的是一个对象 public delegate vo ...

  7. python学习之内置函数(二)

    4.7.3 内置函数(2) int() str() bool() set() list():将一个可迭代对象转化为列表 tuple():将一个可迭代对象转换成元组 dic(): 通过相应的方式创建字典 ...

  8. AspNet Core Swagger4.0 生成请求model描述

    今天给大家分享 swagger 俩个冷门的小技巧 获取控制器描述 将 IncludeXmlComments 方法第二个参数设置为 true 即可 public static void IncludeX ...

  9. Mysql数据库表结构设计准则

    一:动静分离 解释:最好做好静态表和动态表的分离.这里解释一下静态表和动态表的含义,静态表:存储着一些固定不变的资源,比如城市/地区名/国家(静态表一定要使用缓存).动态表:一些频繁修改的表 二:关于 ...

  10. [转帖]中国AI芯“觉醒”的五年

    中国AI芯“觉醒”的五年 https://www.cnbeta.com/articles/tech/857863.htm 原来 海思的营收已经超过了按摩店(AMD) 没想到.. 十多款芯片问世,多起并 ...