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

Posted kirins

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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";
        }
    }
}
View Code

 

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
View Code

以上是关于NPOI导出百万(必须保证你C盘存储空间够大,不然导出失败数据量百万存储的空间需求大)的主要内容,如果未能解决你的问题,请参考以下文章

如何查看手机C.E盘

●导出excel(NPOI)

NPOI Excel导出数据信息

求一个c#winfrom 合并datagridview的效果通过npoi导出也是和dategridview合并效果一样的excel例子

运用NPOI,反射导出EXCEL。

同步以太坊测试网络时导致C盘存储空间不足的解决办法