【NPOI】導出Excel帶圖片


1. 本地路徑圖片

//填寫內容 
for (int i = 0; i < dt.Rows.Count; i++)
{  
    IRow row = sheet.CreateRow(i + 1 + 1);
    row.Height = 80 * 20; //設置excel行高,像素點是1/20
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        if (j == 4)
        {
            var dPath = AppDomain.CurrentDomain.BaseDirectory + dt.Rows[i][j].ToString().Replace(@"/", @"\");
            if (File.Exists(dPath)) //防止文件不存在時報錯
            {
                byte[] picBytes = System.IO.File.ReadAllBytes(dPath);
                int picIndex = workbook.AddPicture(picBytes, NPOI.SS.UserModel.PictureType.JPEG);
                XSSFDrawing patr = (XSSFDrawing)sheet.CreateDrawingPatriarch();
                XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, j, i + 2, j + 1, i + 3);
                XSSFPicture picture = (XSSFPicture)patr.CreatePicture(anchor, picIndex);
            }
        }
        else
        {
            row.CreateCell(j, CellType.String).SetCellValue(dt.Rows[i][j].ToString());
        }
    }
}

2. 網絡路徑圖片

/// <summary>
/// 向sheet插入圖片
/// </summary> 
private static void AddCellPicture(ISheet sheet, XSSFWorkbook workbook, string imgPath, int row, int col)
{
    Uri uri = new Uri(imgPath); //imgPath :網絡圖片地址    
    WebRequest webRequest = WebRequest.Create(uri);

    using (WebResponse webResponse = webRequest.GetResponse())
    {
        //防止發生報錯:GDI+中發生一般性錯誤的解決辦法
        Bitmap bitmap = new Bitmap(webResponse.GetResponseStream()); //讀取圖片流 
        Bitmap OldImage = new Bitmap(bitmap);//將圖片流復制到新的圖片流中 
        bitmap.Dispose();   //將原來的圖片流釋放,將圖片文件進行解鎖。 

        using (MemoryStream ms = new MemoryStream())
        {
            OldImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bytes = ms.ToArray();
            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);  //添加圖片 
            XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row + 2, col + 1, row + 3);
            //圖片位置,圖片左上角為(col, row) 
            XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
            //pict.Resize(); //用圖片原始大小來顯示   
        } 
    }
}

3. 導出Excel

#region 方案商品導出Excel
private static ICellStyle GetTitleCellStyleForScheme(IWorkbook wb)
{
    ICellStyle cellStyle = wb.CreateCellStyle();
    IFont font = wb.CreateFont();

    font.FontName = "微軟雅黑";
    font.FontHeightInPoints = 15;
    font.Boldweight = short.MaxValue;
    cellStyle.SetFont(font);

    //水平對齊  
    cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
    //垂直對齊  
    cellStyle.VerticalAlignment = VerticalAlignment.Center;
    //自動換行  
    cellStyle.WrapText = true;
    return cellStyle;
}

/// <summary>
/// 向sheet插入圖片
/// </summary> 
private static void AddCellPicture(ISheet sheet, XSSFWorkbook workbook, string imgPath, int row, int col)
{
    Uri uri = new Uri(imgPath); //imgPath :網絡圖片地址    
    WebRequest webRequest = WebRequest.Create(uri);

    using (WebResponse webResponse = webRequest.GetResponse())
    {
        Bitmap bitmap = new Bitmap(webResponse.GetResponseStream()); //讀取圖片流 
        Bitmap OldImage = new Bitmap(bitmap);//將圖片流復制到新的圖片流中 
        bitmap.Dispose();   //將原來的圖片流釋放,將圖片文件進行解鎖。 

        using (MemoryStream ms = new MemoryStream())
        {
            OldImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] bytes = ms.ToArray();
            int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);  //添加圖片 
            XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
            XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row + 2, col + 1, row + 3);
            //圖片位置,圖片左上角為(col, row) 
            XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
            //pict.Resize(); //用圖片原始大小來顯示   
        }
    }
}

/// <summary>
/// 導出Excel
/// </summary>
/// <param name="tbScheme"></param>
/// <param name="tbGoods"></param>
/// <param name="sheetName"></param>
/// <param name="exportType">0:基礎數據表;1:報價工具</param>
/// <param name="SchemeBuyWay">4:集采;其他為代發</param>
/// <returns></returns>
public static byte[] ExportExcelForSchemeGoods(DataTable tbScheme, DataTable tbGoods, string sheetName, string exportType, string SchemeBuyWay)
{
    byte[] ret = null;
    string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

    XSSFWorkbook workbook = new XSSFWorkbook();
    ISheet sheet = workbook.CreateSheet(sheetName);
    IRow rowHead = sheet.CreateRow(0);  //首行為方案信息
    rowHead.Height = 50 * 20;
    string strSchemeInfo = string.Empty;
    if (tbScheme != null && tbScheme.Rows.Count > 0)
    {
        strSchemeInfo += "方案編號:" + tbScheme.Rows[0]["SchemeCode"] + ";方案名稱:" + tbScheme.Rows[0]["SchemeName"] + ";單人預算:" + tbScheme.Rows[0]["SingleBudget"] + ";采購人數:" + tbScheme.Rows[0]["BuyNumber"] + ";方案狀態:" + tbScheme.Rows[0]["ApprovalStatusName"] + ";創建人:" + tbScheme.Rows[0]["Creator"] + ";方案有效期:" + tbScheme.Rows[0]["SchemeAgeingTime"];
    }

    //合並單元格顯示方案信息
    if (tbGoods != null && tbGoods.Rows.Count > 0)
    {
        for (int i = 0; i < tbGoods.Columns.Count; i++)
        {
            ICell cell = rowHead.CreateCell(i, CellType.String);
            cell.CellStyle = GetTitleCellStyleForScheme(workbook);
            cell.SetCellValue(strSchemeInfo);
        }

        NPOI.SS.Util.CellRangeAddress range = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, tbGoods.Columns.Count - 1);
        sheet.AddMergedRegion(range);
        rowHead = sheet.CreateRow(1);
        //填寫表頭 
        for (int i = 0; i < tbGoods.Columns.Count; i++)
        {
            if (exportType == "0")    //基礎數據
            {
                if (tbGoods.Columns[i].ColumnName.ToString() == "商品圖片")
                {
                    sheet.SetColumnHidden(i, true);
                    continue;
                }
            }
            if (SchemeBuyWay != "4")  //代發不展示單人采購量
            {
                if (tbGoods.Columns[i].ColumnName.ToString() == "單人份采購量/總采購量")
                {
                    sheet.SetColumnHidden(i, true);
                    continue;
                }
            }
            ICell cell = rowHead.CreateCell(i, CellType.String);
            cell.CellStyle = getHeadCellStyle(workbook);
            cell.SetCellValue(tbGoods.Columns[i].ColumnName.ToString());
        }
        //填寫內容 
        for (int i = 0; i < tbGoods.Rows.Count; i++)
        {
            IRow row = sheet.CreateRow(i + 1 + 1);
            for (int j = 0; j < tbGoods.Columns.Count; j++)
            {
                if (exportType == "1")  //報價工具:帶圖片
                {
                    if (j == 1)
                    {
                        var imgPath = tbGoods.Rows[i][j].ToString();
                        if (imgPath != "")
                        {
                            AddCellPicture(sheet, workbook, imgPath, i, j);
                        }
                    }
                }
                else
                {
                    // 跳過圖片列
                    if (j == 1)
                    {
                        sheet.SetColumnHidden(j, true);
                        continue;
                    }
                }

                if (SchemeBuyWay != "4")    //代發不展示單人采購量
                {
                    if (j == 8)
                    {
                        sheet.SetColumnHidden(j, true);
                        continue;
                    }
                } 

                ICell cell = row.CreateCell(j, CellType.String);
                cell.CellStyle = getTextCellStyle(workbook);
                cell.SetCellValue(tbGoods.Rows[i][j].ToString());

                row.Height = 100 * 20;  //設置默單元格行高
            }
        }

        for (int i = 0; i <= tbGoods.Columns.Count; i++)
        {
            sheet.AutoSizeColumn(i);    //列寬自適應,只對英文和數字有效
            sheet.SetColumnWidth(1, 30 * 256);  //設置圖片列大小 
        }
    }


    using (var ms = new MemoryStream())
    {
        HttpResponse httpResponse = HttpContext.Current.Response;
        httpResponse.Clear();
        httpResponse.Buffer = true;
        httpResponse.Charset = Encoding.UTF8.BodyName;
        httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
        httpResponse.ContentEncoding = Encoding.UTF8;
        httpResponse.ContentType = "application/vnd.ms-excel; charset=UTF-8";
        workbook.Write(httpResponse.OutputStream);
        httpResponse.End();

        ret = ms.ToArray();
        ms.Close();
        ms.Dispose();
    }

    GC.Collect();
    return ret;
}
#endregion
View Code

 


免責聲明!

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



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