将工作表转换为图像以及按页将工作表转换为图像
本文档旨在为开发人员提供详细了解如何将工作表转换为图像文件以及将带有多个页面的工作表转换为每页一个图像文件。
有时,您可能需要将工作表呈现为图片,例如在应用程序或网页中使用。您可能需要将图像插入到Word文档、PDF文件、PowerPoint演示文稿中,或在其他一些场景中使用。简单地说,您希望将工作表呈现为图像。Aspose.Cells API支持将Microsoft Excel文件中的工作表转换为图像。此外,Aspose.Cells支持将工作簿转换为多个图像文件,每个页面一个图像文件。
使用 Aspose.Cells 将工作表转换为图像文件
本文介绍如何使用 Aspose.Cells for Java API 将工作表转换为图像。API 提供了一些有价值的类,比如 SheetRender、ImageOrPrintOptions、WorkbookRender 等。 SheetRender 类表示要为其渲染图像的工作表,并具有重载的 toImage 方法,可以直接将工作表转换为图像文件,而无需设置任何属性或选项。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ConvertWorksheettoImageFile.class) + "TechnicalArticles/"; | |
// Create a new Workbook object | |
// Open a template excel file | |
Workbook book = new Workbook(dataDir + "book1.xlsx"); | |
// Get the first worksheet | |
Worksheet sheet = book.getWorksheets().get(0); | |
// Define ImageOrPrintOptions | |
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); | |
// Specify the image format | |
imgOptions.setImageType(ImageType.JPEG); | |
// Render the sheet with respect to specified image/print options | |
SheetRender render = new SheetRender(sheet, imgOptions); | |
// Render the image for the sheet | |
render.toImage(0, dataDir + "CWToImageFile.jpg"); |
结果
执行上述代码后,名为Sheet1的工作表将被转换为图像文件SheetImage.jpg。
JPG输出
使用Aspose.Cells按页将工作表转换为图像文件
此示例演示如何使用Aspose.Cells将模板工作簿中具有多个页面的工作表转换为每页一个图像文件。
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getSharedDataDir(ConvertWorksheetToImageByPage.class) + "TechnicalArticles/"; | |
// Create a new Workbook object | |
// Open a template excel file | |
Workbook book = new Workbook(dataDir + "ConvertWorksheetToImageByPage.xlsx"); | |
// Get the first worksheet | |
Worksheet sheet = book.getWorksheets().get(0); | |
// Define ImageOrPrintOptions | |
ImageOrPrintOptions options = new ImageOrPrintOptions(); | |
// Set Resolution | |
options.setHorizontalResolution(200); | |
options.setVerticalResolution(200); | |
options.setImageType(ImageType.TIFF); | |
// Sheet2Image by page conversion | |
SheetRender render = new SheetRender(sheet, options); | |
for (int j = 0; j < render.getPageCount(); j++) { | |
render.toImage(j, dataDir + sheet.getName() + " Page" + (j + 1) + ".tif"); | |
} |
结果
执行上述代码后,名为Sheet1的工作表将转换为两个图像文件(每页一个)Sheet 1 Page 1.Tiff和Sheet 1 Page 2.Tiff。
生成的图像文件(Sheet 1 Page 1.Tiff)
生成的图像文件(Sheet 1 Page 2.Tiff)