我的编程空间,编程开发者的网络收藏夹
学习永远不晚

C# 使用Aspose.Cells 导出Excel的步骤及问题记录

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

C# 使用Aspose.Cells 导出Excel的步骤及问题记录

今天在工作中碰到同事用了一种新型的方式导入excel,在此做个学习记录。

Aspose.Cells简介:Aspose.Cells是一款功能强大的Excel文档处理和转换控件,开发人员和客户电脑无需安装Microsoft Excel也能在应用程序中实现类似Excel的强大数据管理功能,支持所有Excel格式类型的操作,在没有Microsoft Excel的环境下,用户也可为其应用程序嵌入类似Excel的强大数据管理功能。

插件:Aspose.Cells

第一步:准备好导出的模板,例子:

C#代码:


#region 验证数据

            if (model == null)
            {
                throw new FriendlyException("无该月结单!");
            }
            var templatePath = @"Template\trade\Cecsc2bHN\分包分供月度结算审批表.xlsx"; ;
            var resFileName = string.Empty;
            var bigTitle = string.Empty;
            var barCodeStr = string.Empty;
            if (string.IsNullOrEmpty(templatePath) || !File.Exists(templatePath))
                throw new FriendlyException("未找到模板文件!");
            #endregion
            #region 初始化模板文件
            var wk = new Workbook(templatePath);
            var designer = new WorkbookDesigner(wk);
            #region 数据重构造
            // 工程形象进度
            #region 构造头部信息
            var topInfo = new Dictionary<string, object>
                { "Title", bigTitle },
                { "ProjectName", model.ProjectName },
                { "Code", barCodeStr }
            };
            MonthSettlementInfo monthInfo = new MonthSettlementInfo()
                CurrentInContractSettlementAmount = 56.32M,
                TerminalInContractSettlementAmount = 123.32M,
                CurrentOutContractSettlementAmount = 6.32M,
                TerminalOutContractSettlementAmount = 5.32M,
                CurrentDeductionSettlementAmount = 12.32M,
                TerminalDeductionSettlementAmount = 26.32M,
                CurrentInContractSafeAmount = 2.32M,
                TerminalInContractSafeAmount = 1.32M,
                CurrentOutContractSafeAmount = 6.32M,
                TerminalOutContractSafeAmount = 8.32M,
                CurrentDeductionSafeAmount = 4.32M,
                TerminalDeductionSafeAmount = 3.32M, 
 
            //形象进度描述
            List<TradeSettleReportProjectProgressItemModel> ProjectProgressList = new List<TradeSettleReportProjectProgressItemModel>();
            for (int i = 0; i < 3; i++)
                TradeSettleReportProjectProgressItemModel Progressmodel = new TradeSettleReportProjectProgressItemModel()
                {
                    ConstractArea = "测试水水水水水水" + i,
                    Remark = "测试模拟的备注" + i,
                    ProgressDesc = "测试撒子怕发送所属" + i,
                    ConstractSite = "场地" + i
                };
                ProjectProgressList.Add(Progressmodel);
            #region 工程名称
  
            //绑定数据到excel中
            //designer.SetDataSource("绑定的到excle的变量名","对应的值")
            designer.SetDataSource("ProgressItem", ProjectProgressList);    //list可以循环绑定  绑定的例子在下面。
            designer.SetDataSource("ProjectName", model.ProjectName);
            designer.SetDataSource("ContractName", model.ContractName);
            designer.SetDataSource("ContractCode", model.ContractCode);
            designer.SetDataSource("MonthSettlementNo", model.MonthSettlementNo);
            designer.SetDataSource("ContractingUnit", model.ContractingUnit);
            designer.SetDataSource("SettlementCode", model.SettlementCode);
            designer.SetDataSource("EnterpriseName", model.EnterpriseName);
            designer.SetDataSource("ThirdPartyName", model.ThirdPartyName);
            designer.SetDataSource("SettlementMonth", model.SettlementMonth);
            designer.SetDataSource("TotalContractAmount", model.TotalContractAmount);
            designer.SetDataSource("SettlementAmountCapitalize", model.SettlementAmountCapitalize);
            #region 尾部
            #endregion 
            designer.Process();
            wk.CalculateFormula(); 
            #region 重新计算行高
            var startRow = 9;
            var endRow = startRow;
            #region 导出文件
            var fileName = $"{model.SettlementMonth.ToString("yyyy年MM月")}{resFileName}.xlsx";
            using (var file = new MemoryStream())
                wk.Save(file, SaveFormat.Xlsx);
                wk.Dispose();
                return new KeyValuePair<string, byte[]>(fileName, file.ToArray());

此种当时的重点是Excel模板的数据绑定:

第一种:单个值的绑定

第二种:列表值的循环绑定

完整代码

Service层:

public KeyValuePair<string, byte[]> ExportSettle(TradeSettleReportModel model)
        {
            #region 验证数据

            if (model == null)
            {
                throw new FriendlyException("无该月结单!");
            }
            var templatePath = @"Template\trade\Cecsc2bHN\分包分供月度结算审批表.xlsx"; ;
            var resFileName = string.Empty;
            var bigTitle = string.Empty;
            var barCodeStr = string.Empty;
            if (string.IsNullOrEmpty(templatePath) || !File.Exists(templatePath))
                throw new FriendlyException("未找到模板文件!");
            #endregion
            #region 初始化模板文件
            var wk = new Workbook(templatePath);
            var designer = new WorkbookDesigner(wk);
            #region 数据重构造
            // 工程形象进度
            #region 构造头部信息
            var topInfo = new Dictionary<string, object>
                { "Title", bigTitle },
                { "ProjectName", model.ProjectName },
                { "Code", barCodeStr }
            };
            MonthSettlementInfo monthInfo = new MonthSettlementInfo()
                CurrentInContractSettlementAmount = 56.32M,
                TerminalInContractSettlementAmount = 123.32M,
                CurrentOutContractSettlementAmount = 6.32M,
                TerminalOutContractSettlementAmount = 5.32M,
                CurrentDeductionSettlementAmount = 12.32M,
                TerminalDeductionSettlementAmount = 26.32M,
                CurrentInContractSafeAmount = 2.32M,
                TerminalInContractSafeAmount = 1.32M,
                CurrentOutContractSafeAmount = 6.32M,
                TerminalOutContractSafeAmount = 8.32M,
                CurrentDeductionSafeAmount = 4.32M,
                TerminalDeductionSafeAmount = 3.32M, 
            //审批记录
            List<TradeSettleReportApprovalCommentsModel> approveModelList = new List<TradeSettleReportApprovalCommentsModel>();
            for (int i = 0; i < 2; i++)
                TradeSettleReportApprovalCommentsModel approveModel = new TradeSettleReportApprovalCommentsModel()
                {
                    Approver = "admin" + i,
                    Comments = "审批通过" + i,
                    NodeName = "测试模板" + i,
                    Seq = i
                };
                approveModelList.Add(approveModel);
            //形象进度描述
            List<TradeSettleReportProjectProgressItemModel> ProjectProgressList = new List<TradeSettleReportProjectProgressItemModel>();
            for (int i = 0; i < 3; i++)
                TradeSettleReportProjectProgressItemModel Progressmodel = new TradeSettleReportProjectProgressItemModel()
                    ConstractArea = "测试水水水水水水" + i,
                    Remark = "测试模拟的备注" + i,
                    ProgressDesc = "测试撒子怕发送所属" + i,
                    ConstractSite = "场地" + i
                ProjectProgressList.Add(Progressmodel);
            #region 工程名称
            designer.SetDataSource("CurrentInContractSettlementAmount", monthInfo.CurrentInContractSettlementAmount);
            designer.SetDataSource("TerminalInContractSettlementAmount", monthInfo.TerminalInContractSettlementAmount);
            designer.SetDataSource("CurrentOutContractSettlementAmount", monthInfo.CurrentOutContractSettlementAmount);
            designer.SetDataSource("TerminalOutContractSettlementAmount", monthInfo.TerminalOutContractSettlementAmount);
            designer.SetDataSource("CurrentDeductionSettlementAmount", monthInfo.CurrentDeductionSettlementAmount);
            designer.SetDataSource("TerminalDeductionSettlementAmount", monthInfo.TerminalDeductionSettlementAmount);
            designer.SetDataSource("CurrentInContractSafeAmount", monthInfo.CurrentInContractSafeAmount);
            designer.SetDataSource("TerminalInContractSafeAmount", monthInfo.TerminalInContractSafeAmount);
            designer.SetDataSource("CurrentOutContractSafeAmount", monthInfo.CurrentOutContractSafeAmount);
            designer.SetDataSource("TerminalOutContractSafeAmount", monthInfo.TerminalOutContractSafeAmount);
            designer.SetDataSource("CurrentDeductionSafeAmount", monthInfo.CurrentDeductionSafeAmount);
            designer.SetDataSource("TerminalDeductionSafeAmount", monthInfo.TerminalDeductionSafeAmount);
            designer.SetDataSource("DetailItem", approveModelList);
            designer.SetDataSource("ProgressItem", ProjectProgressList);
            designer.SetDataSource("ProjectName", model.ProjectName);
            designer.SetDataSource("ContractName", model.ContractName);
            designer.SetDataSource("ContractCode", model.ContractCode);
            designer.SetDataSource("MonthSettlementNo", model.MonthSettlementNo);
            designer.SetDataSource("ContractingUnit", model.ContractingUnit);
            designer.SetDataSource("SettlementCode", model.SettlementCode);
            designer.SetDataSource("EnterpriseName", model.EnterpriseName);
            designer.SetDataSource("ThirdPartyName", model.ThirdPartyName);
            designer.SetDataSource("SettlementMonth", model.SettlementMonth);
            designer.SetDataSource("TotalContractAmount", model.TotalContractAmount);
            designer.SetDataSource("SettlementAmountCapitalize", model.SettlementAmountCapitalize);
            #region 预算编号
            //var _dic = this.GetLaborProSettleInfo(exportDataSource);
            //foreach (var item in _dic)
            //{
            //    designer.SetDataSource(item.Key, item.Value);
            //}
            #region 写入数据
            //foreach (var keyValuePair in topInfo)
            //    designer.SetDataSource(keyValuePair.Key, keyValuePair.Value);
            //designer.SetDataSource("ProjectProgress", exportDataSource.ProjectProgressItems);
            //designer.SetDataSource("MonthEstimate", exportDataSource.MonthEstimateOutputs);
            #region 表1
            //
            Dictionary<string, decimal> dic = new Dictionary<string, decimal>();
            if (dic != null)
                foreach (var item in dic)
                    designer.SetDataSource(item.Key, item.Value);
                }
            #region 尾部
            #region 删除模板sheet
            //wk.Worksheets.RemoveAt(wk.Worksheets["表2"].Index);
            //wk.Worksheets.RemoveAt(wk.Worksheets["表3"].Index);
            designer.Process();
            wk.CalculateFormula();
            #region 插入条形码
            //var barCode = BarCodeGenerator.GetBarCodePNG(barCodeStr);
            //var barCode = BarCodeGenerator.WriteQRCodeImg(barCodeStr);
            //wk.Worksheets[0].Pictures.Add(0, 0, 1, 1, new MemoryStream(barCode));
            //wk.Worksheets[0].Pictures[0].Width = 60;
            #region 重新计算行高
            var startRow = 9;
            var endRow = startRow;
            #region 导出文件
            var fileName = $"{model.SettlementMonth.ToString("yyyy年MM月")}{resFileName}.xlsx";
            using (var file = new MemoryStream())
                wk.Save(file, SaveFormat.Xlsx);
                wk.Dispose();
                return new KeyValuePair<string, byte[]>(fileName, file.ToArray());
        }

Interface层:

KeyValuePair<string, byte[]> ExportSettle(TradeSettleReportModel model);

Controller层:

[AllowAnonymous]
        [HttpPost("Export")]
        public async Task<IActionResult> Export()
        {
            TradeSettleReportModel model = new TradeSettleReportModel()
            {
                ProjectName = "测刷",
                ContractName = "测试合同名称",
                ContractCode = "0010101012E",
                MonthSettlementNo = "0010101012E",
                ContractingUnit = "重庆市",
                SettlementCode = "EW2Z4523",
                EnterpriseName = "WZQ我在钱钱钱",
                ThirdPartyName = "第三方地中四年",
                SettlementMonth = DateTime.Now,
                SettlementAmountCapitalize = "壹拾贰万叁仟壹佰贰拾叁元贰角伍分",

                
            };
            var result = await Task.Run(() => tradeSettleCommonService.ExportSettle(model));
            return File(result.Value, "application/octet-stream", result.Key);
        }

到此这篇关于C# 使用Aspose.Cells 导出Excel的文章就介绍到这了,更多相关C# 导出Excel内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

C# 使用Aspose.Cells 导出Excel的步骤及问题记录

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

如何使用Win7自带的“问题步骤记录器”快速解决系统问题

当我们在使用电脑的过程中遇到问题时,首先可能会去百度一下,或者通过电话、QQ求助别人。但是有时遇到的问题并不能用语言很好的表达出来,最后造成自己说不明白,对方也听不明白的情况,问题没解决不说,还白白耽误了时间。如果能将遇到问题的操作录下来,
2023-06-01

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录