使用Aspose.Cells导出excel

先提供数据源,使用aspose创建excel的单元格和各种样式,插入图片,冻结单元格,行高等

public string ExportDemo()
        {
            ViewResultModel result = ViewResultModel.Create(true, "");
            //获取数据源,为了能通用,转为DataTable,其他类型的数据源也是一样的
            DataTable humanList = Power.Systems.StdSystem.HumanDO.FindAllByTable();
            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("编号", "Code");
            header.Add("姓名", "Name");
            header.Add("部门", "DeptName");
            header.Add("头像", "HeadSmall");
            OutPutFile(header, humanList, "公司人员报表");
            return result.ToJson();
        }
        /// <summary>
        /// 输出文件名
        /// </summary>
        /// <param name="header">编号:Code,姓名:Name....</param>
        /// <param name="dt">数据源,Code,Name.....</param>
        /// <param name="filename">文件名</param>
        private void OutPutFile(Dictionary<string, string> header, DataTable dt, string filename)
        {
            Workbook workbook = new Workbook(); //工作簿
            Worksheet sheet = workbook.Worksheets[0]; //工作表
            Cells cells = sheet.Cells;//单元格
            /*
             * 预计格式为
             *                 人员信息
             * ------------------------------------------
             * |编号|       |姓名|      |部门|     |头像|
             * ------------------------------------------
             *  0001         张三        信息部     picture
             *  ……
             */
            //为标题设置样式     
            Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
            styleTitle.Font.Color = System.Drawing.Color.FromArgb(255, 99, 71);//字体颜色RBG颜色
            styleTitle.ForegroundColor = System.Drawing.Color.FromArgb(250, 240, 230);//背景颜色RBG颜色
            styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
            styleTitle.Font.Name = "宋体";//文字字体
            styleTitle.Font.Size = 18;//文字大小
            styleTitle.Font.IsBold = true;//粗体


            //列头样式
            Style styleHeader = workbook.Styles[workbook.Styles.Add()];//新增样式
            styleHeader.HorizontalAlignment = TextAlignmentType.Center;//文字居中
            styleHeader.Font.Name = "宋体";//文字字体
            styleHeader.Font.Size = 14;//文字大小
            styleHeader.Font.IsBold = true;//粗体
            styleHeader.IsTextWrapped = true;//单元格内容自动换行
            //上下左右增加细边框线
            styleHeader.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
            styleHeader.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
            styleHeader.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
            styleHeader.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

            //普通单元格样式
            Style styleContent = workbook.Styles[workbook.Styles.Add()];//新增样式
            styleContent.HorizontalAlignment = TextAlignmentType.Left;//文字靠左
            styleContent.Font.Name = "宋体";//文字字体
            styleContent.Font.Size = 12;//文字大小
            //styleContent.IsTextWrapped = true;//单元格内容自动换行
            styleContent.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.DashDot;
            styleContent.Borders[BorderType.RightBorder].LineStyle = CellBorderType.DashDot;
            styleContent.Borders[BorderType.TopBorder].LineStyle = CellBorderType.DashDot;
            styleContent.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.DashDot;

            //生成 标题行    
            cells.Merge(0, 0, 1, header.Keys.Count);//合并单元格 ,标题行有几列就合并几列
            cells[0, 0].PutValue(filename);//填写内容
            cells[0, 0].SetStyle(styleTitle);//使用标题样式
            cells.SetRowHeight(0, 50);//第0行,50px高

            //生成  列头行  
            int headerNum = 0;//当前表头所在列
            foreach (string item in header.Keys)
            {
                cells[1, headerNum].PutValue(item);
                cells[1, headerNum].SetStyle(styleHeader);
                cells.SetColumnWidthPixel(headerNum, 200);//设置单元格200宽度
                cells.SetRowHeight(1, 30);//第一行,30px高
                headerNum++;
            }

            //生成数据行
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                cells.SetRowHeight(2 + i, 24);
                int contentNum = 0;//当前内容所在列
                foreach (string item in header.Keys)
                {
                    string value = dt.Rows[i][header[item]] == null ? "" : dt.Rows[i][header[item]].ToString();
                    if (item == "头像")
                    {
                        cells[2 + i, contentNum].SetStyle(styleContent);//单元格样式
                        //获取头像的文件流
                        if (dt.Rows[i][header[item]] != null &&
                            dt.Rows[i][header[item]].ToString() != "00000000-0000-0000-0000-000000000000")
                        {
                            //通过Id找到附件表,此处是获取图片的 文件流,各自不同的方法得到最终的文件流即可
                            Power.Systems.Systems.DocFileDO docfile = Power.Systems.Systems.DocFileDO.FindByKey(value);
                            if (docfile != null)
                            {
                                string ServerUrl = docfile.ServerUrl;
                                string Ip = Power.Global.PowerGlobal.FTPIp;
                                string Port = Power.Global.PowerGlobal.FTPPort;
                                string UserId = Power.Global.PowerGlobal.FTPUserId;
                                string UserPwd = Power.Global.PowerGlobal.FTPUserPwd;//UserPwd
                                string filePath = "ftp://" + Ip + ":" + Port + ServerUrl;
                                byte[] fileData = Power.Global.FtpHelper.FtpfileDownLoad(filePath, UserId, UserPwd).GetBuffer();
                                if (fileData.Length > 0)
                                {
                                    System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData);
                                    System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                                    Bitmap img = PercentImage(image);//压缩图片

                                    int height = img.Height;
                                    System.IO.MemoryStream mss = new System.IO.MemoryStream( );
                                    img.Save(mss,System.Drawing.Imaging.ImageFormat.Png);
                                    sheet.Pictures.Add(2 + i, contentNum, mss, 100, 100);//加入图片,后面是宽度和高度的缩放比例

                                    cells.SetRowHeight(2 + i, height);//设置行高
                                }

                            }
                        }

                    }
                    else
                    {
                        cells[2 + i, contentNum].PutValue(value);
                        cells[2 + i, contentNum].SetStyle(styleContent);
                    }
                    contentNum++;
                }
            }

            sheet.FreezePanes(2, 0, 2, header.Keys.Count);//冻结标题行

            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            workbook.Save(Response, HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xlsx", Aspose.Cells.ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsx));
            //直接显示PDF
            //Aspose.Cells.PdfSaveOptions pdfopt = new Aspose.Cells.PdfSaveOptions(Aspose.Cells.SaveFormat.Pdf);
            //pdfopt.AllColumnsInOnePagePerSheet = true;

            //workbook.Save(Response, HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".pdf", Aspose.Cells.ContentDisposition.Inline, pdfopt);
        }
        private Bitmap PercentImage(Image srcImage)
        {

            int newW = srcImage.Width < 150 ? srcImage.Width : 150;

            int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString());

            try
            {

                Bitmap b = new Bitmap(newW, newH);

                Graphics g = Graphics.FromImage(b);

                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;

                g.DrawImage(srcImage, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);

                g.Dispose();

                return b;

            }

            catch (Exception)
            {

                return null;

            }

        }

Aspose.Cells是一个用于处理Excel文件的.NET组件。在使用Aspose.Cells导出Excel文件时,可以使用以下代码示例: ```csharp System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; workbook.Save(Response, HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xlsx", Aspose.Cells.ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsx)); ``` 这段代码将Excel文件保存到HttpResponse中,以便将其作为附件下载。其中,`workbook`是你创建的Excel工作簿对象,`filename`是你想要保存的文件名。 在生成Excel文件时,你还可以设置标题行和列头行的样式,例如: ```csharp // 生成标题行 cells.Merge(0, 0, 1, header.Keys.Count); // 合并单元格,标题行有几列就合并几列 cells\[0, 0\].PutValue(filename); // 填写内容 cells\[0, 0\].SetStyle(styleTitle); // 使用标题样式 cells.SetRowHeight(0, 50); // 第0行,50px高 // 生成列头行 int headerNum = 0; // 当前表头所在列 foreach (string item in header.Keys) { cells\[1, headerNum\].PutValue(item); cells\[1, headerNum\].SetStyle(styleHeader); cells.SetColumnWidthPixel(headerNum, 200); // 设置单元格200宽度 cells.SetRowHeight(1, 30); // 第一行,30px高 headerNum++; } ``` 这段代码示例展示了如何设置标题行和列头行的样式,其中`cells`是你创建的Worksheet对象,`header`是一个包含列头信息的字典,`styleTitle`和`styleHeader`是你定义的样式对象。 希望这些代码示例能帮助到你导出Excel文件使用Aspose.Cells。 #### 引用[.reference_title] - *1* *2* *3* [使用Aspose.Cells导出excel](https://blog.csdn.net/rxbtalent/article/details/99818241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值