C#生成Excel保存到服務器端並下載


using MongoDB.Bson;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using Zluo.CMember.Entity;
using Zluo.CMember.Interface;
using Zluo.CMember.Service;
using Zluo.CMember.Web.RequestParam;
using Zluo.CMember.Web.RequestParam.Account;
using Zluo.CMember.Web.RequestParam.Order;
using Zluo.Common;
using Zluo.Common.CMember;
using Zluo.SessionCached;
public void CreateExport()
        {
            try
            {
                string fileName = "ErrorSongIds.xls"; // 文件名稱 
                string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload") + "/" + fileName;
                // 1.檢測是否存在文件夾,若不存在就建立個文件夾 
                string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); }
                // 2.解析單元格頭部,設置單元頭的中文名稱 
                HSSFWorkbook workbook = new HSSFWorkbook();
                // 工作簿 
                ISheet sheet = workbook.CreateSheet("失敗歌曲");
                // 工作表 
                IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue("原始ID");
                row.CreateCell(1).SetCellValue("歌曲名稱");
                row.CreateCell(2).SetCellValue("歌手名");
                row.CreateCell(3).SetCellValue("失敗原因");
                //_songListService.getErrorExcel(uid);
                BsonArray array = null;
                int rowIndex = 1; BsonDocument bd = null;
                if (array != null && array.Count > 0)
                {
                    for (int i = 0; i < array.Count; i++)
                    {
                        IRow rowTmp = sheet.CreateRow(rowIndex);
                        bd = (BsonDocument)array[i];
                        if (bd != null)
                        {
                            rowTmp.CreateCell(0).SetCellValue(bd.GetValue("sourceId").ToString());
                            rowTmp.CreateCell(1).SetCellValue(bd.GetValue("songName").ToString());
                            rowTmp.CreateCell(2).SetCellValue(bd.GetValue("singerName").ToString());
                            rowTmp.CreateCell(3).SetCellValue(string.IsNullOrEmpty(bd.GetValue("errorReason").ToString()) ? "" : bd.GetValue("errorReason").ToString());
                            rowIndex++;
                        }
                    }
                }
                // 4.生成文件 
                FileStream file = new FileStream(filePath, FileMode.Create);
                workbook.Write(file); file.Close();
                Response.AppendHeader("Content-Disposition", "attachment;filename=ErrorSongIds.xls");
                Response.ContentType = "application/ms-excel";
                Response.WriteFile(filePath);
                Response.Flush();
                Response.End();
            }
            catch (Exception ex) { throw ex; }
        }

 由於沒有找到哪里上傳文件,需要NPOI.dll文件的給我留言哈,見諒咯。

 

附加動態加載Excel列和合並單元格的代碼:

public void CreateExport()
        {
            try
            {string fileName = "Members.xls"; // 文件名稱 
                string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Template") + "/" + fileName;
                // 1.檢測是否存在文件夾,若不存在就建立個文件夾 
                string directoryName = Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                // 2.解析單元格頭部,設置單元頭的中文名稱 
                HSSFWorkbook workbook = new HSSFWorkbook();

                // 工作簿 
                ISheet sheet = workbook.CreateSheet("會員列表");

                #region 設置Excel表格第一行的樣式
                IRow titleInfo = sheet.CreateRow(0);
                ICell cellTitle = titleInfo.CreateCell(0);
                cellTitle.SetCellValue("會員信息批量錄入模板");
                ICellStyle titleStyle = workbook.CreateCellStyle();
                IFont titleFont = workbook.CreateFont();
                titleFont.FontHeightInPoints = 25;
                titleFont.Boldweight = short.MaxValue;//字體加粗 
                titleStyle.SetFont(titleFont);
                cellTitle.CellStyle = titleStyle;

                #endregion


                IRow dataFields = sheet.CreateRow(2);


                ICellStyle style = workbook.CreateCellStyle();//創建樣式對象 
                style.Alignment = HorizontalAlignment.CENTER;//水平對齊
                style.VerticalAlignment = VerticalAlignment.CENTER;//垂直對齊
                IFont font = workbook.CreateFont(); //創建一個字體樣式對象 
                font.FontName = "宋體"; //和excel里面的字體對應 
                font.Color = new HSSFColor.RED().GetIndex();//顏色參考NPOI的顏色對照表(替換掉PINK()) 
                font.FontHeightInPoints = 10;//字體大小 
                font.Boldweight = short.MaxValue;//字體加粗 
                style.SetFont(font); //將字體樣式賦給樣式對象
                sheet.SetColumnWidth(0, 20 * 256);//設置列寬

                string[] colums = { "*會員卡號", "*會員手機", "*會員姓名", "*會員等級", "會員性別", "電子郵箱", "會員狀態", "固定電話", "永久有效", "身份證號", "開卡費用", "會員地址", "備注信息" };
                ICell Cell = null;
                for (int i = 0; i < colums.Count(); i++)
                {
                    Cell = dataFields.CreateCell(i);
                    Cell.CellStyle = style;
                    Cell.SetCellValue(colums[i]);
                    sheet.SetColumnWidth(i, 17 * 256);
                }
                sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, colums.Count()));//合並單元格
                // 4.生成文件 
                FileStream file = new FileStream(filePath, FileMode.Create);
                workbook.Write(file); file.Close();
                Response.AppendHeader("Content-Disposition", "attachment;filename=Members.xls");
                Response.ContentType = "application/ms-excel";
                Response.WriteFile(filePath);
                Response.Flush();
                Response.End();
            }
            catch (Exception ex) { throw ex; }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM