【办公软件】C# NPOI 操作Excel 案例

news/2024/7/21 5:53:35 标签: c#, excel

文章目录

    • 1、加入NPOI 程序集,使用nuget添加程序集
    • 2、引用NPOI程序集
    • 3、设置表格样式
    • 4、excel加载图片
    • 5、导出excel


1、加入NPOI 程序集,使用nuget添加程序集

在这里插入图片描述

2、引用NPOI程序集

private IWorkbook ExportExcel(PrintQuotationOrderViewModel model)
        {
            //if (model == null) return string.Empty;
            string tempDirPath = Server.MapPath("/Templates/Excel/");
            if (!Directory.Exists(tempDirPath))
            {
                Directory.CreateDirectory(tempDirPath);
            }
            IWorkbook workbook;
            string excelTempPath = tempDirPath + "quotaExcelTemp-new.xls";
            //加载excel模板
            using (FileStream fs = new FileStream(excelTempPath, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
                workbook = new HSSFWorkbook(fs);
            }

            ISheet sheet = workbook.GetSheetAt(0);
            sheet.GetRow(7).GetCell(1).SetCellValue(model.QuotationOrder.QuotedOn.ToString("yyyy-MM-dd"));

            sheet.GetRow(7).GetCell(6).SetCellValue(model.QuotationOrder.Number);

            sheet.GetRow(7).GetCell(9).SetCellValue(model.QuotationOrder.CustomerPurchaseNumber);
            //甲方
            sheet.GetRow(8).GetCell(1).SetCellValue(model.QuotationOrder.Buyer.Company.Name);
            sheet.GetRow(9).GetCell(1).SetCellValue(model.QuotationOrder.Buyer.Name);
            sheet.GetRow(10).GetCell(1).SetCellValue(model.QuotationOrder.Buyer.Email);
            sheet.GetRow(11).GetCell(1).SetCellValue(model.QuotationOrder.Receiver.Mobile);
            sheet.GetRow(12).GetCell(1).SetCellValue(model.QuotationOrder.Receiver.Address);

            //乙方
            sheet.GetRow(8).GetCell(8).SetCellValue("XXXXX有限公司");
            ICellStyle cstyle = workbook.CreateCellStyle();
            cstyle.Alignment = HorizontalAlignment.Left;
            sheet.GetRow(8).GetCell(8).CellStyle = cstyle;

            sheet.GetRow(9).GetCell(8).SetCellValue(model.QuotationOrder.SalesmanName);
            sheet.GetRow(9).GetCell(8).CellStyle = cstyle;

            sheet.GetRow(10).GetCell(8).SetCellValue(model.QuotationOrder.Salesman.Mobile);

            sheet.GetRow(10).GetCell(8).CellStyle = cstyle;

            sheet.GetRow(11).GetCell(8).SetCellValue(model.QuotationOrder.Salesman.Email);
            sheet.GetRow(11).GetCell(8).CellStyle = cstyle;

            int count = model.QuotationItems.Count;
            for (int i = 0; i < count; i++)
            {

                //设置列头的单元格样式
                HSSFCellStyle cellStyle = workbook.CreateCellStyle() as HSSFCellStyle;

                IRow row = sheet.CopyRow(1, 15 + i);
                ICell cell = row.CreateCell(0);
                cell.SetCellValue((i + 1));
                ICellStyle style1 = SetCellStyle((HSSFWorkbook)workbook, HorizontalAlignment.Left);
                cell.CellStyle = style1;

                cell = row.CreateCell(1);
                cell.SetCellValue(model.QuotationItems[i].Product.Name);
                cell.CellStyle = style1;

                cell = row.CreateCell(2);
                cell.CellStyle = style1;
                //合并单元格
                CellRangeAddress region = new CellRangeAddress(15 + i, 15 + i, 1, 2);
                sheet.AddMergedRegion(region);

                cell = row.CreateCell(3);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].CustomCode);
                cell = row.CreateCell(4);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Product.Code);
                cell = row.CreateCell(5);
                cell.CellStyle = style1;
                cell.SetCellValue("PCS");
                cell = row.CreateCell(6);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Quantity);
                cell = row.CreateCell(7);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Quotation.DispatchDays >= 0 ? ((int)model.QuotationItems[i].Quotation.DispatchDays).ToString() : "");
                cell = row.CreateCell(8);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Quotation.UnitPriceWithTax >= 0 ? ((decimal)model.QuotationItems[i].Quotation.UnitPriceWithTax).ToString("f2") : "");
                cell = row.CreateCell(9);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Quotation.SubtotalWithTax.ToString("f2"));
                cell = row.CreateCell(10);
                cell.CellStyle = style1;
                cell.SetCellValue(model.QuotationItems[i].Remark);
            }

            sheet.GetRow(15 + count).GetCell(1).SetCellValue(model.QuotationOrder.Shipping.Amount.ToString("f2"));
            sheet.GetRow(15 + count).GetCell(4).SetCellValue(model.QuotationOrder.TotalWithTax.ToString("f2"));
            sheet.GetRow(15 + count).GetCell(7).SetCellValue(model.QuotationOrder.TotalWithTaxInChinese);
            sheet.GetRow(20 + count).GetCell(2).SetCellValue(model.Payment);

            return workbook;
        }

3、设置表格样式

/// <summary>
        /// 给Excel添加边框
        /// </summary>
        private  ICellStyle SetCellStyle(HSSFWorkbook hssfworkbook, HorizontalAlignment ha)
        {
            ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
            cellstyle.Alignment = ha;
            
            //有边框
            cellstyle.BorderBottom = BorderStyle.Thin;
            cellstyle.BorderLeft = BorderStyle.Thin;
            cellstyle.BorderRight = BorderStyle.Thin;
            cellstyle.BorderTop = BorderStyle.Thin;
            return cellstyle;
        }

excel_135">4、excel加载图片

  HSSFPatriarch patriarch = (HSSFPatriarch)sheet.DrawingPatriarch;
  HSSFClientAnchor anchor = new HSSFClientAnchor(10, 10, 0, 60, 7, 26 + count, 11, 38 + count);
  HSSFPicture picture = (HSSFPicture)patriarch.CreatePicture(anchor, LoadImage(tempDirPath + "1.png", (HSSFWorkbook)workbook));

LoadImage 方法

private int LoadImage(string path, HSSFWorkbook wb)
        {
            FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[file.Length];
            file.Read(buffer, 0, (int)file.Length);
            return wb.AddPicture(buffer, PictureType.PNG);

        }

excel_156">5、导出excel

var stream = new MemoryStream();
var work = ExportExcel(printQuotationOrderViewModel);
   work.Write(stream);
   //mvc代码
   return File(stream.GetBuffer(), "application/vnd.ms-excel", quotedOrderModel.Number + ".xls");    

http://www.niftyadmin.cn/n/5275367.html

相关文章

android —— PopupWindow

一、常用方法&#xff1a; 1、设置显示的位置 // 一个参数 popupWindow.showAsDropDown(v); //参数1: popupWindow关联的view // 参数2和3&#xff1a;相对于关联控件的偏移量popupWindow.showAsDropDown(View anchor, int xoff, int yoff)2、是否会获取焦点 popupWindow.se…

2023.12.20 python基础语法

目录 1.注释 2.变量基础语法 3. 标识符 4.数据类型转换 5.算数运算符 6.复合运算符 JAVA 编译型语言 -- 编译器 Python 解释型语言 -- 解释器 pycharm选择解释器 --- setting --- project -- prthon interpreter -- 选择python 3.9 三引号既可以是多行注释,也可以…

解锁商业宝藏:迅软科技答疑保护商业秘密的重要性

商业秘密指不为公众所知悉、具有商业价值并经权利人采取相应保密措施的技术信息、经营信息等商业信息&#xff0c;一旦泄露可能会给公司带来极大的经济损失和竞争压力&#xff0c;保护商业秘密既能维护企业自身合法权益&#xff0c;也能保障市场经济长期健康发展需求。 保护商…

2024中国(江西)国际金属暨冶金工业展览会-将于3月召开

2024中国&#xff08;江西&#xff09;国际金属暨冶金工业展览会-将于3月召开 时间&#xff1a;2024年3月28-30日 地点&#xff1a;南昌国际博览中心 “世界钨都”“世界铜都”“亚洲锂都”“稀土王国” 【江西诸多第一】 新中国第一架飞机、第一辆柴油轮式拖拉机、第一辆…

Mac如何搭建本地服务器

苹果电脑Mac OS X系统自带了Apache服务器 打开终端 //开启apache&#xff1a;sudo apachectl start //重启apache&#xff1a;sudo apachectl restart //关闭apache&#xff1a;sudo apachectl stop在浏览器输入127.0.10.1 &#xff0c; 如果页面出现 it works&#xff0c;则…

C/C++ 控制台窗口光标移动位置实现(Linux/Windows)

Linux 为打印控制字符实现 Windows 为WINAPI控制台接口实现 功能&#xff1a; 移动到上一行 移动到下一行 定位控制台光标位置到指定X,Y坐标 static bool MoveConsoleCursorPositionToPreviousNextLine(bool previous, int line) noexcept {if (line < 0) {return fals…

vue3 在vite.config中无法使用import.meta.env.*的解决办法

第一种,优先使用第一种方法,其中参数mode就是自定义--mode的值,如果没写,就是production或development import { loadEnv } from vite export default ({ mode }) > {return defineConfig({plugins: [vue()],base:loadEnv(mode, process.cwd()).VITE_APP_NAME}) } 第二种 …

【SQL】根据年月,查询月份中每一天的数据量

传入YYYY-MM-01&#xff0c;查询这个月中每一天的数据量&#xff0c;没有数据的天数用0表示 WITH RECURSIVE DateRange AS (SELECT :startDate AS DateUNION ALLSELECT DATE_ADD(Date, INTERVAL 1 DAY) FROM DateRangeWHERE Date < LAST_DAY(:startDate) ) SELECTdr.Date,CO…