Microsoft® Conversão de arquivos Excel via Java

Salve documentos Excel Microsoft como planilha, web, imagem e formatos de layout fixo

 

Para qualquerConversor Excel aplicativo ou solução, a Biblioteca Excel Java acelera a programação de planilhas e os processos de conversão enquanto lida com vários formatos, incluindo XLS, XLSX, XLSM, XLSB, XLTX, XLTM, CSV, SpreadsheetML, 076193 481. Também permite converter arquivos Excel para PDF*, XPS, HTML, MHTML, texto simples e formatos de imagem populares como TIFF, JPG, PNG, BMP e SVG.

Interconversão de formatos Excel Microsoft

A interconversão do formato de planilha requer apenas o carregamento de uma planilha com uma instância de Pasta de trabalho e salvando de volta no formato desejado enquanto seleciona o valor apropriado em Salvar formato enumeração.

Java Código de exemplo para conversão de formato de arquivo Excel
// load the source file
var wkb = new Workbook("sourceFile.xls");
// save as XLSX, ODS, SXC & FODS formats
wkb.save("xlsx-output.xlsx", SaveFormat.XLSX);
wkb.save("ods-output.ods", SaveFormat.ODS);
wkb.save("scx-output.scx", SaveFormat.SXC);
wkb.save("fods-output.fods", SaveFormat.FODS);
 

Converter Excel para PDF, XPS, HTML e MD

Classes especializadas estão disponíveis para controlar o processo de conversão para formatos de saída específicos, como Opções de salvamento de PDF para converter arquivos Excel como PDF, Opções XpsSave para exportar Excel como XPS, HtmlSaveOptions para renderizar o Excel como HTML e MarkdownSaveOptions para conversão de Excel para Markdown.

Java Código de exemplo para Excel para PDF e formatos da Web
// load template Excel file from disc
var bk = new Workbook("source-file.xlsx");

// convert Excel to PDF using Java
// Create PDF options
PdfSaveOptions options = new PdfSaveOptions();
options.setCompliance(PdfCompliance.PDF_A_1_A);

bk.save("excel-to-pdf.pdf", options);
// save Excel in XPS
bk.save("output.xps", new XpsSaveOptions());
// save Excel in HTML
bk.save("output.html", new HtmlSaveOptions());
// save Excel in Markdown (MD)
bk.save("output.md", new MarkdownSaveOptions());

// one can set relevant save options as of his choice before saving into relevant format
 

Converta JSON para Excel e Excel para JSON

Os dados JSON podem ser importados para uma instância da classe Workbook com a ajuda de JSONUtility.importData para processamento posterior ou conversão simples para qualquer um dos formatos suportados. Da mesma forma, os dados da planilha podem ser exportados como JSON criando um Faixa ou células e ligando para o exportRangeToJson método.

Java Código para conversão JSON para Excel
Workbook workbook = new Workbook(path + "source-file.xlsx");
Worksheet wks = workbook.getWorksheets().get(0);
		
// Read File
File file = new File(path + "source-data.json");
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String jsonInput = "";
String tempString;
while ((tempString = bufferedReader.readLine()) != null) {
	jsonInput = jsonInput + tempString; 
}
bufferedReader.close();
							
// Set JsonLayoutOptions
JsonLayoutOptions options = new JsonLayoutOptions();
options.setIgnoreArrayTitle(true);
options.setArrayAsTable(true);

// Import JSON Data
JSONUtility.importData(jsonInput, wks.getCells(), 0, 0, options);

// Save Excel file
workbook.save(path + "excel-to-json.out.xlsx");
Código-fonte Java para Excel para conversão JSON
// load XLSX file with an instance of Workbook
Workbook workbook = new Workbook("sourceFile.xlsx");
// access CellsCollection of the worksheet containing data to be converted
Cells cells = workbook.getWorksheets().get(0).getCells();
// create & set ExportRangeToJsonOptions for advanced options
ExportRangeToJsonOptions exportOptions = new ExportRangeToJsonOptions();
// create a range of cells containing data to be exported
Range range = cells.createRange(0, 0, cells.getLastCell().getRow() + 1, cells.getLastCell().getColumn() + 1);
// export range as JSON data
String jsonData = JsonUtility.exportRangeToJson(range, exportOptions);
// write data to disc in JSON format
BufferedWriter writer = new BufferedWriter(new FileWriter("output.json"));
writer.write(jsonData);
writer.close();    
 

Salvar planilhas do Excel em imagens

Cada planilha pode ser convertida em diferentes formatos de imagem, incluindo JPG, BMP, PNG e GIF, definidos pela propriedade ImageType. Para qualquerConverter Excel em imagens caso, selecione o caso relevante nos links.

Java Código para conversão de Excel em imagem
// load template spreadsheet
var wkb = new Workbook("template.xlsx");

// Create an object for ImageOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();

// Set the image type
imgOptions.setImageType(ImageType.PNG);

// Get the first worksheet.
Worksheet sheet = wkb.getWorksheets().get(0);

// Create a SheetRender object for the target sheet
SheetRender sr = new SheetRender(sheet, imgOptions);
for (int j = 0; j < sr.getPageCount(); j++) {
	// Generate an image for the worksheet
	sr.toImage(j, dataDir + "WToImage-out" + j + ".png");
}
 

Converter Microsoft Excel para Word e PowerPoint

É possível carregar qualquer planilha e convertê-la para arquivos Word DOCX e PowerPoint PPTX enquanto estiver usando DocxSaveOptions & Opções PptxSave aulas conforme demonstrado abaixo.

Código Java para Excel para Word e conversão PowerPoint
// load the template file
var wkb = new Workbook("template.xlsx");
// save spreadsheet as DOCX
wkb.save("output.docx", new DocxSaveOptions());
// save spreadsheet as PPTX
wkb.save("output.pptx", new PptxSaveOptions());