Fork me on GitHub

.net webform + npoi 实现文件上传下载

由于公司老系统(一部分vb,一部分webform)需要新增文件上传比对下载功能,下载的文件总是提示‘有无法读取的内容,然后xml错误’,啥啥啥的,但其实打开文件,里面的内容又没有错误。
做完发现主要是自己太菜,不了解MemoryStream类的用法,或者说不了解文件流的概念,最后发现是返回的数据类型不对,下面直接上代码。
service:

public MemoryStream ExcelToMs(List<ResultClass> list, string ModelFile, string action, string SavePath)
{
    XSSFWorkbook workbook;
    using (FileStream fs = new FileStream(ModelFile, FileMode.Open, FileAccess.Read))
    {
        workbook  = new XSSFWorkbook(fs);//这里使用了模板 主要是将样式写入workbook
    }
    #region 樣式
    IFont StyleBody = workbook.CreateFont();
    StyleBody.FontHeightInPoints = 10;
    ICellStyle style = workbook.CreateCellStyle();//创建样式
    style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
    style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
    style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
    style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
    style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
    style.SetFont(StyleBody);
    #endregion

    if (action == "download")//忽略这里,这里是另一个下载的实现(是给的写死的模板,因此不用添加新数据)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            workbook.Write(ms);
            ms.Flush();
            workbook = null;
            return ms;//返回MemoryStream 
        }
    } 
    else
    {
        ISheet sheet = workbook.GetSheetAt(0);
        for (int i = 0; i < list.Count; i++)
        {
            IRow row1 = sheet.CreateRow(i + 1);
            row1.CreateCell(0).SetCellValue(list[i].CPN);
            row1.CreateCell(1).SetCellValue(list[i].PN);
            row1.CreateCell(2).SetCellValue(list[i].SIM_UPSIZE_WEEK);
            row1.CreateCell(3).SetCellValue(list[i].QTY);
            row1.CreateCell(4).SetCellValue(list[i].SUDATE.ToString("yyyy/MM/dd"));
            row1.CreateCell(5).SetCellValue(list[i].REQDATE.ToString("yyyy/MM/dd"));
            row1.CreateCell(6).SetCellValue(list[i].MARK);
            row1.CreateCell(7).SetCellValue(list[i].PN1);
            row1.CreateCell(8).SetCellValue(Convert.ToDouble(list[i].LT));
            row1.CreateCell(9).SetCellValue(Convert.ToDouble(list[i].QTYPER));
            row1.CreateCell(10).SetCellValue(Convert.ToDouble(list[i].USQTY));
            for (int j = 0; j <= 10; j++)
            {
                row1.GetCell(j).CellStyle = style;
            }
        }
        using (FileStream fsout = new FileStream(SavePath, FileMode.Create, FileAccess.ReadWrite))//先临时保存到指定地址
        {
            workbook.Write(fsout);
        }
        using (MemoryStream ms = new MemoryStream())//返回文件流
        {
            workbook.Write(ms);
            ms.Flush();
            workbook = null;
            return ms;
        }
    }            
}

一般处理程序:

else if (context.Request["action"] == "downloadResult")
{
    try
    {
        //將數據轉化為Excel
        string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
        string filePath = str + $@"模板地址\ResultDownLoadModel.xlsx";
        string saveTime = DateTime.Now.ToString("yyyy_MM_dd HHmmss");
        string SavePath = str + $@"临时保存的地址\OUTPUT\xxxxxx {saveTime}.xlsx";
        string fileName = $"保存的文件名 {saveTime}.xlsx";
        UpsizeFcstService service = new UpsizeFcstService();
        using (MemoryStream ms = service.ExcelToMs(数据, filePath, "downloadResult", SavePath))
        {
            byte[] data = ms.ToArray();
            #region 客户端保存
            HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Charset = "UTF-8";
            response.ContentType = "application/vnd.ms-excel";//"application/vnd.ms-excel";
            System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + fileName));
            System.Web.HttpContext.Current.Response.BinaryWrite(data);
            #endregion
        }     
    }
    catch (Exception ex)
    {
        context.Response.Write("<script type='text/javascript'>alert('导出发生异常!'" + ex.Message + "''');window.history.back();</script>");
        return;
    }
}

之前傻乎乎的返回了Iworkbook,这样写就不会出现弹窗有无法读取的内容。

posted @ 2020-06-09 11:39  madman98  阅读(134)  评论(0编辑  收藏  举报