protected static int GetColumnWidth(HSSFSheet sheet, int columnIndex) { return ExcelToHtmlUtils.GetColumnWidthInPx(sheet.GetColumnWidth(columnIndex)); }
/// <summary> /// 在指定位置插入图片,跨Column。ColumnIndex2需大于或等于ColumnIndex1 /// </summary> public static void WirtePic(HSSFWorkbook workbook, HSSFSheet sheet, HSSFPatriarch patriarch, int columnIndex1, int columnIndex2, int rowIndex, string picPath) { if (!File.Exists(picPath)) { return; } if (columnIndex2 < columnIndex1) { throw new Exception("ColumnIndex2需大于或等于ColumnIndex1"); } int dx2 = 1023; int dy2 = 255; HSSFRow row = sheet.GetRow(rowIndex); if (row != null) { int cWidth = 0; for (int i = columnIndex1; i < columnIndex2; i++) { cWidth += sheet.GetColumnWidth(columnIndex1); } using (Image img = Image.FromFile(picPath)) { double w = cWidth * 7.0 / 256.0; double h = (row.Height * 1.32 / 20.0); if (((double)img.Width / (double)img.Height) > (cWidth * 7.0 / 256 / (row.Height * 1.32 / 20))) { double h1 = w * img.Height / img.Width; dy2 = (int)(h1 * 255 / h); if (dy2 < 0) dy2 = 0; if (dy2 > 255) dy2 = 255; } else { double w1 = h * img.Width / img.Height; dx2 = (int)(w1 * 1023 / w); if (dy2 < 0) dy2 = 0; if (dy2 > 1023) dy2 = 1023; } } } HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, dx2, dy2, columnIndex1, rowIndex, columnIndex2, rowIndex); byte[] buff = File.ReadAllBytes(picPath); int pic = workbook.AddPicture(buff, HSSFWorkbook.PICTURE_TYPE_JPEG); anchor.AnchorType = 2; patriarch.CreatePicture(anchor, pic); }