Solución Funcional para el Redimensionamiento de Hojas de Cálculo

Antecedentes

En el artículo sobre la adición de Marcos Ole, hemos explicado cómo agregar un Marco Ole en una presentación de PowerPoint utilizando Aspose.Slides para Java. Para acomodar el problema de cambio de objeto, asignamos la imagen de la hoja de cálculo del área seleccionada al Marco de Objeto OLE del Gráfico. En la presentación de salida, cuando hacemos doble clic en el Marco de Objeto OLE que muestra la imagen de la hoja de cálculo, se activa el Gráfico de Excel. Los usuarios finales pueden realizar cualquier cambio deseado en el Libro de Trabajo de Excel real y luego regresar a la diapositiva correspondiente haciendo clic fuera del Libro de Trabajo de Excel activado. El tamaño del Marco de Objeto OLE cambiará cuando el usuario regrese a la diapositiva. El factor de redimensionamiento será diferente para diferentes tamaños de Marco de Objeto OLE y Libro de Trabajo de Excel incrustado.

Causa del Redimensionamiento

Dado que el Libro de Trabajo de Excel tiene su propio tamaño de ventana, intenta mantener su tamaño original en la primera activación. Por otro lado, el Marco de Objeto OLE tendrá su propio tamaño. Según Microsoft, al activar el Libro de Trabajo de Excel, Excel y PowerPoint negocian el tamaño y aseguran que esté en las proporciones correctas como parte de la operación de incrustación. Según las diferencias en el tamaño de la ventana de Excel y el tamaño / posición del Marco de Objeto OLE, se produce el redimensionamiento.

Solución Funcional

Hay dos soluciones posibles para evitar el efecto de redimensionamiento.* Escalar el tamaño del marco Ole en PPT para que coincida con el tamaño en términos de altura/ancho del número deseado de filas/columnas en el Marco Ole * Mantener el tamaño del marco Ole constante y escalar el tamaño de las filas/columnas participantes para que quepan en el tamaño del marco Ole seleccionado.

Escalar el tamaño del marco Ole al tamaño de las filas/columnas seleccionadas de la hoja de cálculo

En este enfoque, aprenderemos cómo establecer el tamaño del marco Ole del Libro de Trabajo de Excel incrustado equivalente al tamaño acumulativo del número de filas y columnas participantes en la hoja de cálculo de Excel.

Ejemplo

Supongamos que hemos definido una plantilla de hoja de cálculo de Excel y deseamos agregarla a la presentación como un marco Ole. En este escenario, el tamaño del Marco de Objeto OLE se calculará primero en función de la altura acumulativa de las filas y los anchos de las columnas de las filas y columnas del libro de trabajo participantes respectivamente. Luego estableceremos el tamaño del marco Ole a ese valor calculado. Para evitar el mensaje de Objeto Incrustado en rojo para el marco Ole en PowerPoint, también obtendremos la imagen de las porciones deseadas de filas y columnas en el Libro de Trabajo y estableceremos eso como la imagen del marco Ole.

try {
WorkbookDesigner workbookDesigner = new WorkbookDesigner();
Workbook workbook = new Workbook("AsposeTest.xls");
workbookDesigner.setWorkbook(workbook);
Presentation presentation = new Presentation("AsposeTest.ppt");
ISlide slide = presentation.getSlides().get_Item(0);
//Setting Ole frame according to Row, Columns
AddOLEFrame(slide, 0, 15, 0, 3, 0, 300, 1100, 0, 0, presentation, workbookDesigner, true, 0, 0);
presentation.save("AsposeTest_Ole.pptx", SaveFormat.Pptx);
} catch (Exception e) {
}
private static void AddOLEFrame(ISlide slide, int startRow, int endRow, int startCol, int endCol,
int dataSheetIdx, int x, int y, double OleWidth, double OleHeight,
Presentation presentation, WorkbookDesigner workbookDesigner,
boolean onePagePerSheet, int outputWidth, int outputHeight) throws Exception//String sheetName,
{
String path="D:\\";
String tempFileName = path +"tempImage";
if (startRow == 0)
{
startRow++;
endRow++;
}
//Setting active sheet index of workbook
workbookDesigner.getWorkbook().getWorksheets().setActiveSheetIndex (dataSheetIdx);
SetWorkBookArea(startRow, endRow, startCol, endCol, dataSheetIdx, workbookDesigner);
//Getting Workbook and selected worksheet
Workbook workbook = workbookDesigner.getWorkbook();
Worksheet work=workbook.getWorksheets().get(dataSheetIdx);
Dimension SlideOleSize=SetOleAccordingToSelectedRowsCloumns(workbook, startRow, endRow, startCol, endCol, dataSheetIdx);
OleWidth = SlideOleSize.getWidth();
OleHeight = SlideOleSize.getHeight();
//Set Ole Size in Workbook
workbook.getWorksheets().setOleSize(startRow, endRow, startCol, endCol);
work.setGridlinesVisible( false);
//Setting Image Options to take the worksheet Image
ImageOrPrintOptions imageOrPrintOptions = new ImageOrPrintOptions();
imageOrPrintOptions.setImageFormat(com.aspose.cells.ImageFormat.getBmp());
imageOrPrintOptions.setOnePagePerSheet( onePagePerSheet);
SheetRender render = new SheetRender(work, imageOrPrintOptions);
String ext = ".bmp";
render.toImage(0, tempFileName + ext);
BufferedImage tempImage = ImageIO.read(new File(tempFileName + ext));
BufferedImage image = ScaleImage(tempImage, outputWidth, outputHeight);
String newTempFileName = "NewTemp";
ImageIO.write(image,"bmp", new File(newTempFileName+ext));
//Adding Image to slide picture collection
//Creating a stream to hold the image file
InputStream iStream = new BufferedInputStream(new FileInputStream(newTempFileName+ext));
IPPImage imgx = null;
imgx = presentation.getImages().addImage(iStream);
//Saving worbook to stream and copying in byte array
ByteArrayOutputStream mstream = new ByteArrayOutputStream ();
workbook.save(mstream,com.aspose.cells.SaveFormat.EXCEL_97_TO_2003);
//Adding Ole Object frame
IOleObjectFrame oleObjectFrame = slide.getShapes().addOleObjectFrame(x, y, (int)OleWidth,(int)OleHeight, "Excel.Sheet.8", mstream.toByteArray());
//Setting ole frame Imnae and Alternative Text property
oleObjectFrame.getSubstitutePictureFormat().getPicture().setImage(imgx);
oleObjectFrame.setAlternativeText( "image." + imgx.getContentType());
}
private static java.awt.Dimension SetOleAccordingToSelectedRowsCloumns(Workbook workbook, int startRow, int endRow, int startCol,
int endCol, int dataSheetIdx)
{
Worksheet work = workbook.getWorksheets().get(dataSheetIdx);
double actualHeight = 0, actualWidth = 0;
for (int i = startRow; i <= endRow; i++)
actualHeight += work.getCells().getRowHeightInch(i);
for (int i = startCol; i <= endCol; i++)
actualWidth += work.getCells().getColumnWidthInch(i);
//Setting new Row and Column Height
double width=0, height=0;
width=actualWidth * 576;
height=actualHeight * 576;
return new java.awt.Dimension((int)(width), (int)(height));
}
private static BufferedImage ScaleImage(BufferedImage image, int outputWidth, int outputHeight)
{
if (outputWidth == 0 && outputHeight == 0)
{
outputWidth = image.getWidth();
outputHeight = image.getHeight();
}
//BufferedImage outputImage=new BufferedImage();
BufferedImage resized = new BufferedImage(outputWidth, outputHeight, image.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, outputWidth, outputHeight, 0, 0,image.getWidth(), image.getHeight(), null);
g.dispose();
return resized;
}
private static void SetWorkBookArea(int startRow, int endRow, int startCol, int endCol,
int dataSheetIdx, WorkbookDesigner workbookDesigner)
{
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setPrintArea( PrintArea(startRow, endRow, startCol, endCol));
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setBottomMargin(0);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setFooterMargin(0);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setTopMargin (0);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setLeftMargin ( 0);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setRightMargin ( 0);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setZoom (100);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setPrintGridlines(false);
workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx).getPageSetup().setPrintQuality( 600);
}
private static String PrintArea(int startRow, int endRow, int startCol, int endCol)
{
return ExcelColumnLetter(startCol) + startRow + ":" + ExcelColumnLetter(endCol) + endRow;
}
private static String ExcelColumnLetter(int intCol)
{
int intFirstLetter = ((intCol) / 26) + 64;
int intSecondLetter = (intCol % 26) + 65;
char letter1 = (intFirstLetter > 64) ? (char)intFirstLetter : ' ';
String tem=Character.toString(letter1) + Character.toString((char)intSecondLetter);
return tem.trim();
}

Escalar la altura de filas y el ancho de columnas de la hoja de cálculo según el tamaño del marco Ole

En este enfoque, aprenderemos cómo escalar las alturas de las filas participantes y el ancho de la columna participante de acuerdo con el tamaño del marco ole establecido

Ejemplo

Supongamos que hemos definido una plantilla de hoja de cálculo de Excel y deseamos agregarla a la presentación como marco Ole. En este escenario, estableceremos el tamaño del marco Ole y escalaremos el tamaño de las filas y columnas que participan en el área del marco Ole. Luego guardaremos el libro de trabajo en un flujo para guardar los cambios y convertirlo en un arreglo de bytes para agregarlo en el marco Ole. Para evitar el mensaje de Objeto Incrustado en rojo para el marco Ole en PowerPoint, también obtendremos la imagen de las porciones deseadas de filas y columnas en el Libro de Trabajo y estableceremos eso como la imagen del marco Ole.

try {
WorkbookDesigner workbookDesigner = new WorkbookDesigner();
Workbook workbook = new Workbook("AsposeTest.xls");
workbookDesigner.setWorkbook(workbook);
Presentation presentation = new Presentation("AsposeTest.ppt");
ISlide slide = presentation.getSlides().get_Item(0);
//Setting Ole frame according to Row, Columns
AddOLEFrame(slide, 0, 15, 0, 3, 0, 300, 1100, 0, 0, presentation, workbookDesigner, true, 0, 0);
presentation.save("AsposeTest_Ole.pptx", SaveFormat.Pptx);
} catch (Exception e) {
}
private static void SetOleAccordingToCustomHeighWidth(Workbook workbook, int startRow,
int endRow, int startCol, int endCol, double slideWidth, double slideHeight, int dataSheetIdx)
{
Worksheet work = workbook.getWorksheets().get(dataSheetIdx);
double actualHeight = 0, actualWidth = 0;
double newHeight = slideHeight;
double newWidth = slideWidth;
double tem = 0;
double newTem = 0;
for (int i = startRow; i <= endRow; i++)
actualHeight += work.getCells().getRowHeightInch(i);
for (int i = startCol; i <= endCol; i++)
actualWidth += work.getCells().getColumnWidthInch(i);
///Setting new Row and Column Height
for (int i = startRow; i <= endRow; i++)
{
tem = work.getCells().getRowHeightInch(i);
newTem = (tem / actualHeight) * newHeight;
work.getCells().setRowHeightInch(i, newTem);
}
for (int i = startCol; i <= endCol; i++)
{
tem = work.getCells().getColumnWidthInch(i);
newTem = (tem / actualWidth) * newWidth;
work.getCells().setColumnWidthInch(i, newTem);
}
}
private static void AddOLEFrame(ISlide slide, int startRow, int endRow, int startCol, int endCol,
int dataSheetIdx, int x, int y, int OleWidth, int OleHeight,
Presentation presentation, WorkbookDesigner workbookDesigner,
Boolean onePagePerSheet, int outputWidth, int outputHeight)
{
try {
String path = "D:\\";
String tempFileName = path +"tempImage";
if (startRow == 0)
{
startRow++;
endRow++;
}
//Setting active sheet index of workbook
workbookDesigner.getWorkbook().getWorksheets().setActiveSheetIndex(dataSheetIdx);
//Getting Workbook and selected worksheet
Workbook workbook = workbookDesigner.getWorkbook();
Worksheet work=workbook.getWorksheets().get(dataSheetIdx);
//Scaling rows height and coluumns width according to custom Ole size
double height = OleHeight / 576f;
double width = OleWidth / 576f;
SetOleAccordingToCustomHeighWidth(workbook, startRow, endRow, startCol, endCol, width, height, dataSheetIdx);
//Set Ole Size in Workbook
workbook.getWorksheets().setOleSize(startRow, endRow, startCol, endCol);
workbook.getWorksheets().get(0).setGridlinesVisible(false);
//Setting Image Options to take the worksheet Image
ImageOrPrintOptions imageOrPrintOptions = new ImageOrPrintOptions();
imageOrPrintOptions.setImageFormat(ImageFormat.getBmp());
imageOrPrintOptions.setOnePagePerSheet(onePagePerSheet);
SheetRender render = new SheetRender(workbookDesigner.getWorkbook().getWorksheets().get(dataSheetIdx), imageOrPrintOptions);
String ext = ".bmp";
render.toImage(0, tempFileName + ext);
BufferedImage tempImage = ImageIO.read(new File(tempFileName + ext));
BufferedImage image = ScaleImage(tempImage, outputWidth, outputHeight);
String newTempFileName = "NewTemp";
ImageIO.write(image,"bmp", new File(newTempFileName+ext));
//Adding Image to slide picture collection
//Creating a stream to hold the image file
InputStream iStream = new BufferedInputStream(new FileInputStream(newTempFileName+ext));
IPPImage imgx = null;
imgx = presentation.getImages().addImage(iStream);
//Saving worbook to stream and copying in byte array
ByteArrayOutputStream mstream = new ByteArrayOutputStream ();
workbook.save(mstream,com.aspose.cells.SaveFormat.EXCEL_97_TO_2003);
//Adding Ole Object frame
OleObjectFrame oleObjectFrame = (OleObjectFrame) slide.getShapes().addOleObjectFrame(x, y, (int)OleWidth,(int)OleHeight, "Excel.Sheet.8", mstream.toByteArray());
//Setting ole frame Imnae and Alternative Text property
oleObjectFrame.getSubstitutePictureFormat().getPicture().setImage(imgx);
oleObjectFrame.setAlternativeText( "image." + imgx.getContentType());
} catch (Exception e) {
}
}
private static BufferedImage ScaleImage(BufferedImage image, int outputWidth, int outputHeight)
{
if (outputWidth == 0 && outputHeight == 0)
{
outputWidth = image.getWidth();
outputHeight = image.getHeight();
}
//BufferedImage outputImage=new BufferedImage();
BufferedImage resized = new BufferedImage(outputWidth, outputHeight, image.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(image, 0, 0, outputWidth, outputHeight, 0, 0,image.getWidth(), image.getHeight(), null);
g.dispose();
return resized;
}

Conclusión