首页 技术 正文
技术 2022年11月23日
0 收藏 323 点赞 3,631 浏览 8226 个字

十年河东,十年河西,莫欺少年穷!

NPOI支持对 Word 和 Excel 文件的操作!

针对 Word 的操作一般用于打印技术!说白了就是利用 Word 文件作为模板,生成各种不同的打印!具体用到的技术是:Word 关键字替换操作,Word 图片插入操作, Word 表格填充操作,Word 图表生成操作等等,在此就不一一介绍了,有兴趣的小虎斑可以参考鄙人博客:专业 web 打印组件 及 C# web项目利用docx文档作为模板~为打印专做的解决方案

针对 Excel 文件的操作一般常用的就两种:

1、将数据库数据导入至Excel

2、将 Excel 中数据导入至数据库

当然,针对Excel文件的操作也有其他优秀的组件实现,譬如:Spire.XLS,关于这个组件的运用,大家可参考我的博客:Spire.XLS,生成Excel文件、加载Excel文件

好了,说了这么多,咱们进入正题:

其实说到正题,也没什么可说的,都是一些代码,会调用就行了。

源代码如下:

using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;namespace KMHC.Infrastructure.Excel
{
public class ExcelHelper
{
#region DataTable导出至Excel
/// <summary>
/// 导出至Excel
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="templateName">Xls文件名 仅支持Xls扩展名</param>
/// <returns></returns>
public static string LoadForToExcel(DataTable dt, string templateName)
{
string mapPath = HttpContext.Current.Server.MapPath(VirtualPathUtility.GetDirectory("~"));
string path = string.Format(@"{0}Templates\{1}.xls", mapPath, templateName);
GridToExcelByNPOI(dt, path);
return path;
}
/// <summary>
/// 导出至Excel具体实现
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="strExcelFileName">文件路径</param>
private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName )
{
HSSFWorkbook workbook = new HSSFWorkbook();
try
{
ISheet sheet = workbook.CreateSheet("Sheet1"); ICellStyle HeadercellStyle = workbook.CreateCellStyle();
HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//字体
NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
headerfont.Boldweight = (short)FontBoldWeight.Bold;
HeadercellStyle.SetFont(headerfont); //用column name 作为列名
int icolIndex = ;
IRow headerRow = sheet.CreateRow();
foreach (DataColumn item in dt.Columns)
{
ICell cell = headerRow.CreateCell(icolIndex);
cell.SetCellValue(item.ColumnName);
cell.CellStyle = HeadercellStyle;
icolIndex++;
} ICellStyle cellStyle = workbook.CreateCellStyle(); //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
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; NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
cellfont.Boldweight = (short)FontBoldWeight.Normal;
cellStyle.SetFont(cellfont); //建立内容行
int iRowIndex = ;
int iCellIndex = ;
foreach (DataRow Rowitem in dt.Rows)
{
IRow DataRow = sheet.CreateRow(iRowIndex);
foreach (DataColumn Colitem in dt.Columns)
{ ICell cell = DataRow.CreateCell(iCellIndex);
cell.SetCellValue(Rowitem[Colitem].ToString());
cell.CellStyle = cellStyle;
iCellIndex++;
}
iCellIndex = ;
iRowIndex++;
} //自适应列宽度
for (int i = ; i < icolIndex; i++)
{
sheet.AutoSizeColumn(i);
} //写Excel
FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
workbook.Write(file);//将Excel文件保存到项目中
file.Flush();
file.Close(); //Log.WriteLog("导出Excel成功!");
}
catch (Exception ex)
{
//Log.WriteLog("导出Excel异常:", ex);
}
finally
{
workbook = null;
} }
#endregion #region Excel文件数据导出至DataTable
/// <summary>
/// Excel数据导出至DataTable
/// </summary>
/// <param name="templateName">文件名</param>
/// <param name="strTableName"></param>
/// <param name="iSheetIndex">第几个Sheet的数据</param>
public static DataTable LoadForToDataTable(string templateName, string strTableName, int iSheetIndex)
{
string mapPath = HttpContext.Current.Server.MapPath(VirtualPathUtility.GetDirectory("~"));//获取项目根目录
string path = string.Format(@"{0}Templates\{1}.xls", mapPath, templateName);//Templates 构造根目录路径 Templates 是项目的一个文件夹
return XlSToDataTable(path, strTableName, iSheetIndex);
}
/// <summary>
/// Excel文件导成Datatable
/// </summary>
/// <param name="strFilePath">Excel文件目录地址</param>
/// <param name="strTableName">Datatable表名</param>
/// <param name="iSheetIndex">Excel sheet index</param>
/// <returns></returns>
private static DataTable XlSToDataTable(string strFilePath, string strTableName, int iSheetIndex)
{ string strExtName = Path.GetExtension(strFilePath); DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(strTableName))
{
dt.TableName = strTableName;
} if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
{
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(iSheetIndex); //列头
foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
{
dt.Columns.Add(item.ToString(), typeof(string));
} //写入内容
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while (rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
if (row.RowNum == sheet.FirstRowNum)
{
continue;
} DataRow dr = dt.NewRow();
foreach (ICell item in row.Cells)
{
switch (item.CellType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Formula:
switch (item.CachedFormulaResultType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string str = item.StringCellValue;
if (!string.IsNullOrEmpty(str))
{
dr[item.ColumnIndex] = str.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string strValue = item.StringCellValue;
if (!string.IsNullOrEmpty(strValue))
{
dr[item.ColumnIndex] = strValue.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
}
dt.Rows.Add(dr);
}
}
} return dt;
}
#endregion
}
}

具体调用如下:

 public string Export()
{////自己构造泛型:AllList
//打印开始 自己构造泛型:AllList
DataTable dt = new DataTable();
dt.Columns.Add("所属", typeof(string));
dt.Columns.Add("消费日期", typeof(string));
dt.Columns.Add("消费项", typeof(string));
dt.Columns.Add("类别", typeof(string));
dt.Columns.Add("会员卡", typeof(string));
dt.Columns.Add("现金", typeof(string));
dt.Columns.Add("支付宝", typeof(string));
dt.Columns.Add("微信", typeof(string));
dt.Columns.Add("一卡通", typeof(string));
foreach (var item in AllList)
{
DataRow dr = dt.NewRow();
dr["所属"] = "";
if (item.ServiceType.HasValue)
{
var dicModelForService = dicListForService.FirstOrDefault(A => A.ItemCode == item.ServiceType.ToString());
if (dicModelForService != null)
{
dr["所属"] = dicModelForService.ItemName;
}
}
try
{
dr["消费日期"] = item.FeeDate.ToString("yyyy-MM-dd");
}
catch
{
dr["消费日期"] = "";
}
dr["消费项"] = item.FeeName;
dr["类别"] = "";
if (item.FeeType.HasValue)
{
var dicModel = dicList.FirstOrDefault(A => A.ItemCode == item.FeeType.ToString());
if (dicModel != null)
{
dr["类别"] = dicModel.ItemName;
}
}
//
dr["会员卡"] = item.ResidentCard.HasValue ? Convert.ToDouble(-item.ResidentCard).ToString("0.00") : "";
dr["现金"] = item.Cash.HasValue ? Convert.ToDouble(-item.Cash).ToString("0.00") : "";
dr["支付宝"] = item.Alipay.HasValue ? Convert.ToDouble(-item.Alipay).ToString("0.00") : "";
dr["微信"] = item.WeChatpay.HasValue ? Convert.ToDouble(-item.WeChatpay).ToString("0.00") : "";
dr["一卡通"] = item.AllPurposeCard.HasValue ? Convert.ToDouble(-item.AllPurposeCard).ToString("0.00") : "";
dt.Rows.Add(dr);
} return ExcelHelper.LoadForToExcel(dt, "FeeDetails");
}

前端Action视图代码如下:

   public ActionResult Export()
{
IReportManageService service = IOCContainer.Instance.Resolve<IReportManageService>();
string pth = service.Export();
System.Web.HttpContext.Current.Response.Charset = "GB2312";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("Content-type", "application/ms-excel");
Response.AddHeader("Accept-Ranges", "bytes");
Response.AddHeader("Content-Length", new System.IO.FileInfo(pth).Length.ToString());
Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddhhssmm") + ".xls");
Response.WriteFile(pth);
Response.End();
return View();
}

以上便是所有源代码,希望大家喜欢!

截图如下:

C# Npoi 实现Excel与数据库相互导入

@陈卧龙的博客

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,993
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845