打开NPOI创建的excel文件时出错

时间:2015-01-26 13:06:00

标签: c# asp.net asp.net-mvc-4 npoi

我正在使用NPOI将数据导出到excel。我正在强制将文件作为用户的附件下载。当用户将文件保存在磁盘上并打开文件时,它可以正常工作,但在尝试从下载对话框中选择打开选项时会失败。请参阅下面的代码。不确定有什么问题

var xssfworkbook = new XSSFWorkbook();
            var sheet1 = xssfworkbook.CreateSheet("Sheet 1");

            //make  header row

            var row1 = sheet1.CreateRow(0);

            var cell0 = row1.CreateCell(0);
            cell0.SetCellValue("Firm Id");

            var cell1 = row1.CreateCell(1);
            cell1.SetCellValue("Account Number");

for (int i = 0; i < result.Count; i++)
            {
                var row = sheet1.CreateRow(i + 1);

                if (result[i].FeeAmount != null)
                {
                    var cellFirmID = row.CreateCell(0);
                    cellFirmID.SetCellValue(result[i].FirmID);
                }

                if (result[i].AccountNumber != null)
                {
                    var cellAccountNumber = row.CreateCell(1);
                    cellAccountNumber.SetCellValue(result[i].AccountNumber);
                }
}

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", "BESTINVEST_fee_rebate_loader_.xlsx"));
MemoryStream file = WriteToStream(xssfworkbook);
response.Clear();
response.BinaryWrite(file.ToArray());
response.End();





        private MemoryStream WriteToStream(XSSFWorkbook xssfworkbook)
        {
            MemoryStream file = new MemoryStream();
            xssfworkbook.Write(file);
            return file;
        }

2 个答案:

答案 0 :(得分:0)

我建议您确保您的手机已解锁。

我没有问题地使用以下内容:

                var workbook = new XSSFWorkbook();
            var members = (obj as IEnumerable<MemberListViewModel>).ToDataSourceResult(request).Data;
            var sheet = workbook.CreateSheet(TempData["List"].ToString());
            var headerRow = sheet.CreateRow(0);

            headerRow.CreateCell(0).SetCellValue("Name");
            headerRow.CreateCell(1).SetCellValue("Degrees");
            headerRow.CreateCell(2).SetCellValue("Rank");
            headerRow.CreateCell(3).SetCellValue("Endowed Professorship");
            headerRow.CreateCell(4).SetCellValue("Department");
            headerRow.CreateCell(5).SetCellValue("Program");

            var font = workbook.CreateFont();
            font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
            XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
            style.SetFont(font);
            style.FillPattern = NPOI.SS.UserModel.FillPattern.SolidForeground;
            style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
            style.IsLocked = false;
            style.WrapText = true;

            for (int i = 0; i < 6; i++)
            {
                var colStyle = sheet.GetColumnStyle(i);
                colStyle.WrapText = !colStyle.WrapText;
                sheet.SetDefaultColumnStyle(i, colStyle);
                var cell = headerRow.Cells[i];
                cell.CellStyle = style;
            }
            headerRow.RowStyle = style;


            sheet.SetColumnWidth(0, 30 * 256);
            sheet.SetColumnWidth(1, 20 * 256);
            sheet.SetColumnWidth(2, 20 * 256);
            sheet.SetColumnWidth(3, 50 * 256);
            sheet.SetColumnWidth(4, 30 * 256);
            sheet.SetColumnWidth(5, 50 * 256);

            int rowNumber = 1;
            style = (XSSFCellStyle)workbook.CreateCellStyle();
            style.IsLocked = false;
            style.WrapText = true;
            foreach (MemberListViewModel member in members)
            {
                var row = sheet.CreateRow(rowNumber++);

                row.CreateCell(0).SetCellValue(member.FullName);
                row.CreateCell(1).SetCellValue(member.degrees);
                row.CreateCell(2).SetCellValue(member.rank);
                row.CreateCell(3).SetCellValue(member.endowed_professorship);
                row.CreateCell(4).SetCellValue(member.department);
                row.CreateCell(5).SetCellValue(member.program);
            }
            //var colStyle = sheet.GetColumnStyle(3);
            //colStyle.WrapText = !colStyle.WrapText;
            //sheet.SetDefaultColumnStyle(3, colStyle);

            workbook.Write(output);

            var fileName = String.Format(
                            "{0} {2} - {1}.xlsx",
                            DateTime.Now.ToString("yyyyMMdd-HHmmss"),
                            Utilities.getUsername(Utilities.GetCurrentUser()), TempData["List"]).Replace(":", "");
            var file = File(output.ToArray(), Utilities.ExcelFileContentType, fileName);

            var context = System.Web.HttpContext.Current;
            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
            context.Response.AddHeader("content-disposition", String.Format("inline;filename=\'{0}\'", fileName));
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.ContentType = file.ContentType;
            context.Response.AddHeader("content-length", file.FileContents.Length.ToString());
            context.Response.BinaryWrite(buffer: file.FileContents.ToArray());
            context.Response.Flush();
            context.Response.End();
            output.Dispose();

答案 1 :(得分:0)

这个问题来自“文化”。在创建Excel之前:

var culture=new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture=culture;
Thread.CurrentThread.CurrentUICulture=culture;