NPOI导出百万(必须保证你C盘存储空间够大,不然导出失败【数据量百万存储的空间需求大】)

1、NPOI版本为2.4.1

2、

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Web;
using NPOI.HSSF.Util;
using NPOI.SS.Util;
using TM.Medical.ToolUtility.Tools;
using NPOI.XSSF.Streaming;

namespace UtilityNPOI
{
    public class NPOIHelper
    {
        private HSSFWorkbook hssfworkbook;
        private ISheet sheet1;

        /// <summary>
        /// 导出中心药物明细
        /// </summary>
        /// <param name="excelModels"></param>
        /// <param name="fileName"></param>
        /// <param name="serverPath"></param>
        /// <returns></returns>
        public static string GetDrugInfoUrlBig(List<ExcelNewModel> excelModels, string fileName, string serverPath,string projectName, string projectTitle, string generatedTime)
        {
            SXSSFWorkbook sxssfBook = new SXSSFWorkbook();
            sxssfBook.RandomAccessWindowSize = 1000;
            int sheetIndex = 0;
            foreach (var excelModel in excelModels)
            {
                var dtSource = excelModel.ResultDataTable;
                var fieldDictionarys = excelModel.FieldDictionarys;
                var title = excelModel.Title;
                NPOI.SS.UserModel.ISheet sheet = sxssfBook.CreateSheet(title);
                ICellStyle dateStyle = sxssfBook.CreateCellStyle();
                IDataFormat format = sxssfBook.CreateDataFormat();

                if (sheetIndex==0)
                {
                    int rowCounts = dtSource.Rows.Count + 1 + 4;
                    int cellCounts = dtSource.Columns.Count;

                    //设置样式  居中 字体
                    ICellStyle style0 = sxssfBook.CreateCellStyle();
                    style0.VerticalAlignment = VerticalAlignment.Center;
                    style0.Alignment = HorizontalAlignment.Center;
                    IFont font1 = sxssfBook.CreateFont();
                    font1.FontHeight = 15 * 15;
                    font1.IsBold = true;
                    style0.SetFont(font1);

                    ICellStyle style = sxssfBook.CreateCellStyle();
                    style.VerticalAlignment = VerticalAlignment.Center;
                    style.Alignment = HorizontalAlignment.Center;
                    IFont font = sxssfBook.CreateFont();
                    style.SetFont(font);

                    ICellStyle style2 = sxssfBook.CreateCellStyle();
                    IFont font2 = sxssfBook.CreateFont();
                    font2.FontHeight = 15 * 15;
                    font1.IsBold = true;
                    style2.SetFont(font2);

                    Create(sheet, 5, cellCounts);
                    //建创行
                    ICell cell0 = sheet.GetRow(0).GetCell(0);
                    cell0.SetCellValue(fileName); //药物明细表
                    sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, cellCounts));
                    cell0.CellStyle = style0;

                    ICell cell1 = sheet.GetRow(1).GetCell(0);
                    cell1.SetCellValue(projectTitle + ":" + projectName);//项目名称
                    sheet.AddMergedRegion(new CellRangeAddress(1, 1, 0, cellCounts));
                    cell1.CellStyle = style2;

                    ICell cell2 = sheet.GetRow(2).GetCell(0);
                    cell2.SetCellValue(generatedTime + ":" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));//生成时间
                    sheet.AddMergedRegion(new CellRangeAddress(2, 2, 0, cellCounts));
                    cell2.CellStyle = style2;

                    ICell cell3 = sheet.GetRow(3).GetCell(0);
                    cell3.SetCellValue("");
                    sheet.AddMergedRegion(new CellRangeAddress(3, 3, 0, cellCounts));

                }
                else
                {
                    int cellCounts = dtSource.Columns.Count;
                    Create(sheet, 1, cellCounts);
                }
                int rowCount = dtSource.Rows.Count + 1;
                int cellCount = fieldDictionarys.Count;
                //Create(sheet, 1, cellCount);
                int index = 0;
                if (sheetIndex==0)
                {
                    index = 4;
                }
                int k = 0;
                foreach (var fieldDictionary in fieldDictionarys)
                {
                    string cellValue = fieldDictionary.Key;
                    sheet.GetRow(index).GetCell(k).SetCellValue(cellValue);
                    k++;
                }

                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    int row = index + i + 1;
                    int j = 0;
                    IRow currtRow = sheet.CreateRow(row);
                    foreach (var fieldDictionary in fieldDictionarys)
                    {
                        ICell cell = currtRow.CreateCell(j);
                        string fieldName = fieldDictionary.Value;
                        string cellValue = dtSource.Rows[i][fieldName].ToString();
                        sheet.GetRow(row).GetCell(j).SetCellValue(cellValue);
                        j++;
                    }
                }
                sheetIndex++;
            }
            var patUrl = serverPath;
            if (!FileHelperTools.IsExistDirectory(patUrl))
            {
                FileHelperTools.CreateDirectory(patUrl);
            }
            var partName = UniqueKeyGenerator.GetDtRng_RandomNo();
            using (FileStream fileStream = File.Open(@"" + patUrl + fileName + "-" + partName + ".xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                sxssfBook.Write(fileStream);
                fileStream.Close();
            }
            return "/RandResult/" + fileName + "-" + partName + ".xlsx";
        }

        /// <summary>
        /// 导出药物库存表明细
        /// </summary>
        /// <param name="excelModels"></param>
        /// <param name="fileName"></param>
        /// <param name="serverPath"></param>
        /// <returns></returns>
        public static string GetDrugListStockBig(List<ExcelNewModel> excelModels, string fileName, string serverPath)
        {
            SXSSFWorkbook sxssfBook = new SXSSFWorkbook();
            sxssfBook.RandomAccessWindowSize = 1000;
            int sheetIndex = 0;
            foreach (var excelModel in excelModels)
            {
                var dtSource = excelModel.ResultDataTable;
                var fieldDictionarys = excelModel.FieldDictionarys;
                var title = excelModel.Title;
                NPOI.SS.UserModel.ISheet sheet = sxssfBook.CreateSheet(title);
                ICellStyle dateStyle = sxssfBook.CreateCellStyle();
                IDataFormat format = sxssfBook.CreateDataFormat();
                int rowCount=1;
                if (sheetIndex==0)
                {
                    rowCount=  5;
                }

                int cellCount = fieldDictionarys.Count;
                Create(sheet, rowCount, cellCount);
                int index = 0;
                //第一个sheet添加标题
                if (sheetIndex == 0)
                {
                    foreach (var cellDictionary in excelModel.CellDictionarys)
                    {
                        var key = cellDictionary.Key;
                        var value = cellDictionary.Value;
                        sheet.GetRow(index).GetCell(0).SetCellValue(key);
                        sheet.GetRow(index).GetCell(1).SetCellValue(value);
                        index++;
                    }
                }
                if (excelModel.CellDictionarys!=null)
                {
                    index += 1;
                }

                int k = 0;
                foreach (var fieldDictionary in fieldDictionarys)
                {
                    string cellValue = fieldDictionary.Key;
                    sheet.GetRow(index).GetCell(k).SetCellValue(cellValue);
                    k++;
                }

                for (int i = 0; i < dtSource.Rows.Count; i++)
                {
                    int row = index + i + 1;
                    int j = 0;
                    IRow currtRow = sheet.CreateRow(row);
                    foreach (var fieldDictionary in fieldDictionarys)
                    {
                        ICell cell = currtRow.CreateCell(j);
                        string fieldName = fieldDictionary.Value;
                        string cellValue = dtSource.Rows[i][fieldName].ToString();
                        sheet.GetRow(row).GetCell(j).SetCellValue(cellValue);
                        j++;
                    }
                }
                sheetIndex++;
            }
            var patUrl = serverPath;
            if (!FileHelperTools.IsExistDirectory(patUrl))
            {
                FileHelperTools.CreateDirectory(patUrl);
            }
            var partName = UniqueKeyGenerator.GetDtRng_RandomNo();
            using (FileStream fileStream = File.Open(@"" + patUrl + fileName + "-" + partName + ".xlsx", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                sxssfBook.Write(fileStream);
                fileStream.Close();
            }
            return "/RandResult/" + fileName + "-" + partName + ".xlsx";
        }
    }
}

3、这个传递的参数希望亲们能看懂

  1 #region 药物库存表导出1048576
  2         [HttpPost]
  3         public async Task<ApiRes<ExportModelRespon>> ExpDrugListStockExecl([FromBody]ExpDrugListStockRequest modelRequest)
  4         {
  5
  6             string serverPath = HttpContext.Current.Server.MapPath("/RandResult/");
  7             Task.Factory.StartNew(() => getDrugListStock(modelRequest, serverPath));
  8             var baseModel = new ApiRes<ExportModelRespon>()
  9             {
 10                 Body = new ExportModelRespon(),
 11                 Message = "成功"
 12             };
 13             baseModel.Body.model = "";
 14             return baseModel;
 15         }
 16
 17         private async void getDrugListStock(ExpDrugListStockRequest modelRequest, string serverPath)
 18         {
 19             Log4net.Error("药物库存表导出开始" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
 20
 21             var fileInfoModel = _iSystemExportInfoServices.GetSystemExportInfoModel(projectInfoId, userId, (int)ReportTypeEnum.DrugListStockReport);
 22             if (fileInfoModel != null)
 23             {
 24                 fileInfoModel.IsSuccess = false;
 25                 if (1 != _iSystemExportInfoServices.UpSystemExportInfo(fileInfoModel))
 26                 {
 27                     throw new SeeException(5001, "", "");
 28                 }
 29             }
 30             else
 31             {
 32                 fileInfoModel = new TM_SystemExportInfo()
 33                 {
 34                     Id = Guid.NewGuid().ToString(),
 35                     CompanyId = companyId,
 36                     ProjectId = projectId,
 37                     ProjectInfoId = projectInfoId,
 38                     FilePath = "",
 39                     IsSuccess = false,
 40                     ReportType = (int)ReportTypeEnum.DrugListStockReport,
 41                     UserId = userId,
 42                     CreateTime = DateTime.Now,
 43                 };
 44                 if (1 != _iSystemExportInfoServices.AddSystemExportInfo(fileInfoModel))
 45                 {
 46                     throw new SeeException(5001, "", "");
 47                 }
 48             }
 49             #region  获取药物库存表
 50             string hospitalId = modelRequest.HospitalId;
 51             string language = modelRequest.Language;
 52             if (string.IsNullOrEmpty(hospitalId))
 53             {
 54                 hospitalId = _iDrugListServices.GetHospitalIds(userId, projectInfoId);
 55             }
 56             var model = _iDrugListServices.GetDrugListStockAll(projectInfoId, hospitalId, language);
 57             if (!_iUserGroupServices.IsBlindStatus(userId, projectInfoId))
 58             {
 59                 var drugListStockModels = model.DrugListStockModels;
 60                 var drugListStockDetailModels = model.DrugListStockDetailModels;
 61                 string baseDrug = LanguageTool.LanguageHelper.GetValue(language, "Code129");//不适用
 62                 foreach (var item in drugListStockModels)
 63                 {
 64                     item.DrugType = baseDrug;
 65                     item.DrugBatch = baseDrug;
 66                 }
 67                 foreach (var item in drugListStockDetailModels)
 68                 {
 69                     item.DrugType = baseDrug;
 70                     item.BatchNumer = baseDrug;
 71                     item.ExpiryDate = baseDrug;
 72                 }
 73
 74             }
 75             string planNum = string.Empty;
 76             string projectName = string.Empty;
 77             string applicant = string.Empty;
 78             var ProjectMainModels = _iProjectServices.LoadEntities(p => p.ProjectId == projectId).FirstOrDefault();
 79             if (ProjectMainModels != null)
 80             {
 81                 planNum = ProjectMainModels.PlanNum;
 82                 projectName = ProjectMainModels.ProjectName;
 83                 applicant = ProjectMainModels.Applicant;
 84             }
 85             var projectTitalModel = new ProjectTitleModel
 86             {
 87                 PlanNum = planNum,
 88                 ProjectName = projectName,
 89                 Applicant = applicant
 90             };
 91             model.ProjectTitleModel = projectTitalModel;
 92             #endregion
 93
 94             var hospitalName = LanguageTool.LanguageHelper.GetValue(language, "Code543");//库房|中心
 95             var drugType = LanguageTool.LanguageHelper.GetValue(language, "Code261");//药物治疗类型
 96             var drugBatch = LanguageTool.LanguageHelper.GetValue(language, "Code262");//批次
 97             var unpassNum = LanguageTool.LanguageHelper.GetValue(language, "Code252");//未放行
 98             var useNum = LanguageTool.LanguageHelper.GetValue(language, "Code253");//可用
 99             var retainNum = LanguageTool.LanguageHelper.GetValue(language, "Code557");//转运保留
100             //var val7 = LanguageTool.LanguageHelper.GetValue(language, "Code558");//返还保留
101             var sendNum = LanguageTool.LanguageHelper.GetValue(language, "Code259");//运送中
102             //var val9 = LanguageTool.LanguageHelper.GetValue(language, "Code540");//返还中
103             var freezeNum = LanguageTool.LanguageHelper.GetValue(language, "Code652");//冻结
104             var quarantineNum = LanguageTool.LanguageHelper.GetValue(language, "Code256");//隔离
105             var issueNum = LanguageTool.LanguageHelper.GetValue(language, "Code254");//已发放
106             var backNum = LanguageTool.LanguageHelper.GetValue(language, "Code515");//已回收
107             var destroyNum = LanguageTool.LanguageHelper.GetValue(language, "Code541");//已销毁
108             var loseNum = LanguageTool.LanguageHelper.GetValue(language, "Code398");//丢失
109             var invalidNum = LanguageTool.LanguageHelper.GetValue(language, "Code667");//作废废弃
110             var stainedNum = LanguageTool.LanguageHelper.GetValue(language, "Code542");//污损损坏
111             var dueNum = LanguageTool.LanguageHelper.GetValue(language, "Code257");//已过期
112             Dictionary<string, string> dictionary = new Dictionary<string, string>()
113             {
114                 { hospitalName,"HospitalName"},
115                 { drugType,"DrugType"},
116                 { drugBatch,"DrugBatch"},
117                 { unpassNum,"UnpassNum"},
118                 { useNum,"UseNum"},
119                 { retainNum,"RetainNum"},
120                 { sendNum,"SendNum"},
121                 { freezeNum,"FreezeNum"},
122                 { quarantineNum,"QuarantineNum"},
123                 { issueNum,"IssueNum"},
124                 { backNum,"BackNum"},
125                 { destroyNum,"DestroyNum"},
126                 { loseNum,"LoseNum"},
127                 { invalidNum,"InvalidNum"},
128                 { stainedNum,"StainedNum"},
129                 { dueNum,"DueNum"},
130             };
131             var drugNum = LanguageTool.LanguageHelper.GetValue(language, "Code497");//药物编号
132             var drugTypes = LanguageTool.LanguageHelper.GetValue(language, "Code261");//药物治疗类型
133             var batchNumer = LanguageTool.LanguageHelper.GetValue(language, "Code262");//批次
134             var expiryDate = LanguageTool.LanguageHelper.GetValue(language, "Code247");//效期
135             var hospitalNames = LanguageTool.LanguageHelper.GetValue(language, "Code543");//库房|中心
136             var status = LanguageTool.LanguageHelper.GetValue(language, "Code498");//状态
137             Dictionary<string, string> dictionarys = new Dictionary<string, string>()
138             {
139                 { drugNum,"DrugNum"},
140                 { drugTypes,"DrugType"},
141                 { batchNumer,"BatchNumer"},
142                 { expiryDate,"ExpiryDate"},
143                 { hospitalNames,"HospitalName"},
144                 { status,"Status"},
145             };
146             List<ExcelNewModel> excelModels = new List<ExcelNewModel>();
147             int maxCount = 1048576 - 5; //1048576是EXCEL2007的最大行数,-1是要去掉标题行
148
149             var planNumCell = LanguageTool.LanguageHelper.GetValue(language, "Code121");//方案号
150             var projectNameCell = LanguageTool.LanguageHelper.GetValue(language, "Code536");//项目名称
151             var applicantCell = LanguageTool.LanguageHelper.GetValue(language, "Code537");//申办方
152             var projectTitle = model.ProjectTitleModel;
153             var cellDictionarys = new Dictionary<string, string>();
154             if (projectTitle != null)
155             {
156                 cellDictionarys.Add(planNumCell, projectTitle.PlanNum);
157                 cellDictionarys.Add(projectNameCell, projectTitle.ProjectName);
158                 cellDictionarys.Add(applicantCell, projectTitle.Applicant);
159             }
160             for (int i = 0; i < 15; i++)
161             {
162                 model.DrugListStockModels.AddRange(model.DrugListStockModels);
163             }
164             #region 药物库存表
165             if (model.DrugListStockModels.Count > maxCount)
166             {
167                 int sheetCount = 0;
168                 for (int i = 0; i < model.DrugListStockModels.Count; i = i + maxCount)
169                 {
170                     if (i!=0)
171                     {
172                         cellDictionarys = null;
173                     }
174                     var thisHospitalListSheet = model.DrugListStockModels.Skip(sheetCount * maxCount).Take(maxCount).ToList();
175                     if (i != 0)
176                     {
177                         maxCount = 1048575;
178                         //加1048571(第一张sheet的数据数和其他表的不同)
179                         thisHospitalListSheet = model.DrugListStockModels.Skip((sheetCount-1) * maxCount+ 1048571).Take(maxCount).ToList();
180                     }
181                     var dtHospitalSheet = ToDataTable(thisHospitalListSheet);
182                     sheetCount = sheetCount + 1;
183                     var excelNewModelSheet = new ExcelNewModel
184                     {
185                         CellDictionarys= cellDictionarys,
186                         FieldDictionarys = dictionary,
187                         ResultDataTable = dtHospitalSheet,
188                         Title = "DrugListStock-" + sheetCount.ToString(),
189                         SheetType = 2
190                     };
191                     excelModels.Add(excelNewModelSheet);
192                 }
193             }
194             else
195             {
196                 var dt = ToDataTable(model.DrugListStockModels);
197                 var excelNewModel = new ExcelNewModel
198                 {
199                     CellDictionarys = cellDictionarys,
200                     FieldDictionarys = dictionary,
201                     ResultDataTable = dt,
202                     Title = "DrugListStock",
203                     SheetType = 2
204                 };
205                 excelModels.Add(excelNewModel);
206             }
207             #endregion
208
209
210
211             int maxCounts= 1048576-1;
212             for (int i = 0; i < 10; i++)
213             {
214                 model.DrugListStockDetailModels.AddRange(model.DrugListStockDetailModels);
215             }
216             #region 药物清单
217             if (model.DrugListStockDetailModels.Count > maxCounts)
218             {
219                 int sheetCount = 0;
220                 for (int i = 0; i < model.DrugListStockDetailModels.Count; i = i + maxCounts)
221                 {
222                     var thisHospitalListSheet = model.DrugListStockDetailModels.Skip(sheetCount * maxCounts).Take(maxCounts).ToList();
223                     var dtHospitalSheet = ToDataTable(thisHospitalListSheet);
224                     dtHospitalSheet.Columns.Remove("DrugOrder");
225                     sheetCount = sheetCount + 1;
226                     var excelNewModelSheet = new ExcelNewModel
227                     {
228                         FieldDictionarys = dictionarys,
229                         ResultDataTable = dtHospitalSheet,
230                         Title = "DrugListStockDetail-" + sheetCount.ToString(),
231                         SheetType = 1
232                     };
233                     excelModels.Add(excelNewModelSheet);
234                 }
235             }
236             else
237             {
238                 var dt = ToDataTable(model.DrugListStockDetailModels);
239                 dt.Columns.Remove("DrugOrder");
240                 var excelNewModel = new ExcelNewModel
241                 {
242                     FieldDictionarys = dictionarys,
243                     ResultDataTable = dt,
244                     Title = "DrugListStockDetail",
245                     SheetType = 1
246                 };
247                 excelModels.Add(excelNewModel);
248             }
249             #endregion
250
251             string TableName = LanguageTool.LanguageHelper.GetValue(language, "Code567");
252             string partUrl = NPOIHelper.GetDrugListStockBig(excelModels, "DrugListStock", serverPath);
253             var baseModel = new ApiRes<ExportModelRespon>()
254             {
255                 Body = new ExportModelRespon(),
256                 Message = "成功"
257
258             };
259             baseModel.Body.model = partUrl;
260             string strJson = JsonConvert.SerializeObject(baseModel);
261             fileInfoModel.IsSuccess = true;
262             fileInfoModel.FilePath = partUrl;
263             if (1 != _iSystemExportInfoServices.UpSystemExportInfo(fileInfoModel))
264             {
265                 throw new SeeException(5001, "", "");
266             }
267             Log4net.Error("药物库存表导出结束" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "" + strJson);
268         }
269         #endregion
270         #region 中心药物明细导出1048576
271
272
273         [HttpPost]
274         public async Task<ApiRes<ExportModelRespon>> GetDrugUrl([FromBody]DrugExportRequest modelRequest)
275         {
276
277             #region 药物信息Old
278             //List<string> rowName = new List<string>();
279             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code497"));  //药物编号
280             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code261")); //药物治疗类型
281             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code262"));//批次
282             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code496")); //有效期
283             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code498")); //状态
284             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code123"));//研究中心/仓库
285             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code563")); //转运日期
286             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code564")); //接收日期
287             ////rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code566"));//物流单号
288             //var valPatientNum = LanguageTool.LanguageHelper.GetValue(language, "Code127");
289             //if (IsPatientScreenNoProject(projectInfoId))
290             //{
291             //    //受试者筛选号
292             //    valPatientNum = LanguageTool.LanguageHelper.GetValue(language, "Code659");
293             //}
294             //rowName.Add(valPatientNum);//研究者
295             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code462"));//随机号
296             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code136")); //访视
297             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code532"));//访视日期
298             #endregion
299             string serverPath = HttpContext.Current.Server.MapPath("/RandResult/");
300             Task.Factory.StartNew(() => getDrugInfos(modelRequest, serverPath));
301             var baseModel = new ApiRes<ExportModelRespon>()
302             {
303                 Body = new ExportModelRespon(),
304                 Message = "成功"
305             };
306             baseModel.Body.model = "";
307             return baseModel;
308         }
309
310         private async void getDrugInfos(DrugExportRequest modelRequest, string serverPath)
311         {
312             Log4net.Error("中心药物明细导出开始" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
313
314             var fileInfoModel = _iSystemExportInfoServices.GetSystemExportInfoModel(projectInfoId, userId, (int)ReportTypeEnum.DrugInfoReport);
315             if (fileInfoModel != null)
316             {
317                 fileInfoModel.IsSuccess = false;
318                 if (1 != _iSystemExportInfoServices.UpSystemExportInfo(fileInfoModel))
319                 {
320                     throw new SeeException(5001, "", "");
321                 }
322             }
323             else
324             {
325                 fileInfoModel = new TM_SystemExportInfo()
326                 {
327                     Id = Guid.NewGuid().ToString(),
328                     CompanyId = companyId,
329                     ProjectId = projectId,
330                     ProjectInfoId = projectInfoId,
331                     FilePath = "",
332                     IsSuccess = false,
333                     ReportType = (int)ReportTypeEnum.DrugInfoReport,
334                     UserId = userId,
335                     CreateTime = DateTime.Now,
336                 };
337                 if (1 != _iSystemExportInfoServices.AddSystemExportInfo(fileInfoModel))
338                 {
339                     throw new SeeException(5001, "", "");
340                 }
341             }
342
343             List<DrugAllModel> models = _iDrugServices.GetModelListByAllExport(modelRequest.HospitalId,
344                modelRequest.DrugType, modelRequest.DrugBatch, modelRequest.Status, modelRequest.DrugNumList, userId, projectInfoId);
345             string language = modelRequest.Language;
346             if (!_iUserGroupServices.IsBlindStatus(userId, projectInfoId))
347             {
348                 foreach (var item in models)
349                 {
350                     item.DrugType = LanguageTool.LanguageHelper.GetValue(language, "Code129"); // "不适用"
351                     item.DrugBatchNumber = LanguageTool.LanguageHelper.GetValue(language, "Code129"); // "不适用"
352                     item.ExpiyDateTime = LanguageTool.LanguageHelper.GetValue(language, "Code129");// "不适用"
353                 }
354             }
355             List<DrugAllExportModel> list = new List<DrugAllExportModel>();
356             foreach (var model in models)
357             {
358                 DrugAllExportModel m = new DrugAllExportModel()
359                 {
360                     DrugNum = model.DrugNum,
361                     DrugType = model.DrugType,
362                     DrugBatchNumber = model.DrugBatchNumber,
363                     ExpiyDateTime = model.ExpiyDateTime,
364                     Status = LanguageTool.LanguageHelper.GetEnglishValueByFiledName(language, model.Status),
365                     HospitalName = model.HospitalName,
366                     TransportDate = model.TransportDate,
367                     ReceivedDate = model.ReceivedDate,
368                     Researcher = model.PatNum,
369                     RandomNum = model.RandomNum,
370                     ViewName = model.ViewName,
371                     SendDrugTime = model.SendDrugTime
372                 };
373                 list.Add(m);
374             }
375             //DataTable dt = ToDataTable<DrugAllExportModel>(list);
376
377             string drugNo= LanguageTool.LanguageHelper.GetValue(language, "Code497");  //药物编号1
378             string drugType= LanguageTool.LanguageHelper.GetValue(language, "Code261"); //药物治疗类型2
379             string lot= LanguageTool.LanguageHelper.GetValue(language, "Code262");//批次3
380             string expiryData= LanguageTool.LanguageHelper.GetValue(language, "Code496"); //有效期4
381             string status= LanguageTool.LanguageHelper.GetValue(language, "Code498"); //状态5
382             string hospitalName = LanguageTool.LanguageHelper.GetValue(language, "Code123");//研究中心/仓库6
383             string deliveryDate= LanguageTool.LanguageHelper.GetValue(language, "Code563"); //转运日期7
384             string receivingDate= LanguageTool.LanguageHelper.GetValue(language, "Code564"); //接收日期8
385             //rowName.Add(LanguageTool.LanguageHelper.GetValue(language, "Code566"));//物流单号
386             string valPatientNum = LanguageTool.LanguageHelper.GetValue(language, "Code127");//9
387             if (IsPatientScreenNoProject(projectInfoId))
388             {
389                 //受试者筛选号
390                 valPatientNum = LanguageTool.LanguageHelper.GetValue(language, "Code659");
391             }
392             string randomNum= LanguageTool.LanguageHelper.GetValue(language, "Code462");//随机号10
393             string visit= LanguageTool.LanguageHelper.GetValue(language, "Code136"); //访视11
394             string dispensationTime= LanguageTool.LanguageHelper.GetValue(language, "Code532");//访视日期12
395             Dictionary<string, string> dictionary = new Dictionary<string, string>()
396             {
397                 { drugNo,"DrugNum"},
398                 { drugType,"DrugType"},
399                 { lot,"DrugBatchNumber"},
400                 { expiryData,"ExpiyDateTime"},
401                 { status,"Status"},
402                 { hospitalName,"HospitalName"},
403                 { deliveryDate,"TransportDate"},
404                 { receivingDate,"ReceivedDate"},
405                 { valPatientNum,"Researcher"},
406                 { randomNum,"RandomNum"},
407                 { visit,"ViewName"},
408                 { dispensationTime,"SendDrugTime"}
409             };
410             List<ExcelNewModel> excelModels = new List<ExcelNewModel>();
411             int maxCount = 1048576 - 5; //1048576是EXCEL2007的最大行数,-5是要去掉标题行
412             for (int i = 0; i < 13; i++)
413             {
414                 list.AddRange(list);
415             }
416             if (list.Count > maxCount)
417             {
418                 int sheetCount = 0;
419                 for (int i = 0; i < list.Count; i = i + maxCount)
420                 {
421                     var thisHospitalListSheet = list.Skip(sheetCount * maxCount).Take(maxCount).ToList();
422                     if (i!=0)
423                     {
424                         maxCount = 1048575;
425                         //加1048571(第一张sheet的数据数和其他表的不同)
426                         thisHospitalListSheet = list.Skip((sheetCount - 1) * maxCount+ 1048571).Take(maxCount).ToList();
427                     }
428                     var dtHospitalSheet = ToDataTable(thisHospitalListSheet);
429                     sheetCount = sheetCount + 1;
430                     var excelNewModelSheet = new ExcelNewModel
431                     {
432                         FieldDictionarys = dictionary,
433                         ResultDataTable = dtHospitalSheet,
434                         Title = "DrugInfo-" + sheetCount.ToString(),
435                     };
436                     excelModels.Add(excelNewModelSheet);
437                 }
438             }
439             else
440             {
441                 var dt = ToDataTable(list);
442                 var excelNewModel = new ExcelNewModel
443                 {
444                     FieldDictionarys = dictionary,
445                     ResultDataTable = dt,
446                     Title = "DrugInfo"
447                 };
448                 excelModels.Add(excelNewModel);
449             }
450             string TableName = LanguageTool.LanguageHelper.GetValue(language, "Code567");
451             #region 获取项目信息
452             var ProjectMainModels = new TMProjectModel();
453             if (string.IsNullOrEmpty(companyToken))
454             {
455                 TM_Project project = _iProjectServices.GetByTopOne();
456                 ProjectMainModels = _iProjectServices.GetProjectById(project == null ? "" : project.ProjectId);
457                 Log4net.Error("company:None");
458             }
459             else
460             {
461                 ProjectMainModels = _iProjectServices.GetProjectById(projectId);
462             }
463             #endregion
464
465             //string partUrl = NPOIHelper.getUrlForDrugDetail(dt, rowName, TableName, ProjectMainModels.ProjectName, LanguageTool.LanguageHelper.GetValue(language, "Code536"), LanguageTool.LanguageHelper.GetValue(language, "Code568"));
466             string partUrl = NPOIHelper.GetDrugInfoUrlBig(excelModels, TableName, serverPath, ProjectMainModels.ProjectName, LanguageTool.LanguageHelper.GetValue(language, "Code536"), LanguageTool.LanguageHelper.GetValue(language, "Code568"));
467             var baseModel = new ApiRes<ExportModelRespon>()
468             {
469                 Body = new ExportModelRespon(),
470                 Message = "成功"
471
472             };
473             baseModel.Body.model = partUrl;
474             string strJson = JsonConvert.SerializeObject(baseModel);
475             fileInfoModel.IsSuccess = true;
476             fileInfoModel.FilePath = partUrl;
477             if (1 != _iSystemExportInfoServices.UpSystemExportInfo(fileInfoModel))
478             {
479                 throw new SeeException(5001, "", "");
480             }
481             Log4net.Error("中心药物明细导出结束" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "" + strJson);
482         }
483         #endregion

原文地址:https://www.cnblogs.com/Kirins/p/12022407.html

时间: 2024-11-13 09:38:00

NPOI导出百万(必须保证你C盘存储空间够大,不然导出失败【数据量百万存储的空间需求大】)的相关文章

NPOI大数据量多个sheet导出源码(原)

#region  NPOI大数据量多个sheet导出 /// <summary>        /// 大数据量多个sheet导出        /// </summary>        /// <typeparam name="T">数据源实体类</typeparam>        /// <param name="objList">数据源</param>        /// <p

云诺与传统网盘最大的不同即在于后者更侧重于存储本身,而云诺则更关注用户存储之后怎么更方便地使用这些云端的文件

“我本人就是Dropbox的重度用户.在美国的时候,我家里最夸张的时候一共有六台电脑在用,我经常为了找不到某个文件到底放在哪台电脑里而头痛,D ropbox的出现让我觉得它正是我想要的东西.”王淮顿了顿,接着说道,“不过,即便是这样,我也不是它的付费用户.” 王淮曾是Facebook的早期员工,2011年9月离开F acebook之后回国成为天使投资人.他对南都记者说的这段话,既证明了云存储服务在个人市场上真真实实存在的需求,也说出了这一市场的尴尬所在. 前期的服务器架设已然烧掉了大量资金,但个

SharePoint 2010 升级到2013时 保证用户能够连接但不能修改正升级的数据

SharePoint 2010 升级到2013时 保证用户能够连接但不能修改正升级的数据 我总结的步骤 红色请注意他们的意义. 步骤1:连接到SQL DBS 上的SharePoint 2010数据库的内容. 步骤2:设置SharePoint内容数据库的只读状态为True. 步骤3:把SharePoint 2010内容数据库备份文件恢复到SharePoint 2013场. 步骤4:SharePoint内容数据库的只读状态设置为False(读写). 步骤5:分离SharePoint 2010内容数据

使用内存映射文件MMF实现大数据量导出时的内存优化

前言 导出功能几乎是所有应用系统必不可少功能,今天我们来谈一谈,如何使用内存映射文件MMF进行内存优化,本文重点介绍使用方法,相关原理可以参考文末的连接 实现 我们以单次导出一个excel举例(csv同理),excel包含1~n个sheet,在每个sheet中存储的按行和列的坐标在单元格存储具体数据,如果我们要使用MMF,第一个要考虑的就是如何将整个excel合理的存储到MMF中.这里我们引入MMF两个对象: MemoryMappedFile --表示内存映射文件 MemoryMappedVie

数据量下高并发同步的讲解(不看,保证你后悔

4.常见的提高高并发下访问的效率的手段 首先要了解高并发的的瓶颈在哪里? 1.可能是服务器网络带宽不够 2.可能web线程连接数不够 3.可能数据库连接查询上不去. 根据不同的情况,解决思路也不同. 像第一种情况可以增加网络带宽,DNS域名解析分发多台服务器. 负载均衡,前置代理服务器nginx.apache等等 数据库查询优化,读写分离,分表等等 最后复制一些在高并发下面需要常常需要处理的内容: 尽量使用缓存,包括用户缓存,信息缓存等,多花点内存来做缓存,可以大量减少与数据库的交互,提高性能.

数据恢复软件使用经验-支持U盘,手机SD卡,硬盘数据,解决图片恢复后打不开的问题

数据恢复软件使用经验-支持U盘,手机SD卡,硬盘数据,解决图片恢复后打不开的问题. 用过很多数据恢复软件,最早EasyRecovery pro,恢复过U盘,手机SD卡,硬盘数据.但现在下载不了最新版,而且BAIDU出来的都是国产收费软件假冒的,因为国产恢复软件都太差劲了,所以想偷梁换柱,不仅要收费,而且网上评论恢复效果也很差. 后来用过两款国外crack版的recuva和FinalData,效果也不错,但是有几次帮朋友恢复手机sd卡的时候,照片图片恢复后很多,打不开也不能预览.研究了很长时间,和

批量新增百万条数据 十百万条数据

--创建用户表CREATE TABLE table_1(    id int PRIMARY KEY, -- 主键ID    c1 varchar(24) NOT NULL,-- 列1    c2 datetime NOT NULL -- 列2) -- 批量新增一万条数据CREATE PROCEDURE PROC_INSERT @max int = 1000000, @c1 int = 1as WHILE @c1  <= @maxBEGIN  INSERT INTO Table_1 VALUES

java 导出Excel 大数据量

出处: http://lyjilu.iteye.com/ 分析导出实现代码,XLSX支持: /** * 生成<span style="white-space: normal; background-color: #ffffff;">XLSX</span>,2007版本的excel,每个sheet无6.5W的行数限制,但是到了一定数量,可能内存溢出, * 次方法适合在预计10W以下的数据导出时使用,本机测试,14W可以导出.列数量在8列左右 * * @param

大数据量下高并发同步的讲解(不看,保证你后悔)

对于我们开发的网站,如果网站的访问量非常大的话,那么我们就需要考虑相关的并发访问问题了.而并发问题是绝大部分的程序员头疼的问题, 但话又说回来了,既然逃避不掉,那我们就坦然面对吧~今天就让我们一起来研究一下常见的并发和同步吧. 为了更好的理解并发和同步,我们需要先明白两个重要的概念:同步和异步    1.同步和异步的区别和联系          所谓同步,可以理解为在执行完一个函数或方法之后,一直等待系统返回值或消息,这时程序是出于阻塞的,只有接收到 返回的值或消息后才往下执行其它的命令. 异步