Salvataggio di file Excel in CSV, PDF e altri formati

Diversi modi per salvare i tuoi file

L’API Aspose.Cells fornisce una classe denominata Workbook che rappresenta un file Excel e fornisce tutte le proprietà e i metodi necessari che i programmatori possono avere bisogno per lavorare con i propri file Excel. La classe Workbook fornisce un metodo save che viene utilizzato per salvare i file Excel. Il metodo save ha molte sovraccariche che vengono utilizzate per salvare i file Excel in modi diversi.

I programmatori possono anche specificare il formato del file in cui i loro file dovrebbero essere salvati. I file possono essere salvati in diversi formati come XLS, SpreadsheetML, CSV, tabulato, valori separati da tabulazione TSV, XPS e molti altri. Questi formati di file sono specificati utilizzando l’enumerazione SaveFormat.

L’enumerazione SaveFormat contiene molti formati di file predefiniti (che possono essere scelti da te) come segue:

Tipi di formato file Descrizione
AUTO API cerca di rilevare il formato appropriato dall’estensione del file specificata nel primo parametro del metodo di salvataggio
CSV Rappresenta un file CSV
XLSX Rappresenta un file di foglio di calcolo XML di Open Office
XLSM Rappresenta un file XLSM basato su XML
XLTX Rappresenta un file di modello Excel
XLTM Rappresenta un file di modello abilitato per macro Excel
XLAM Rappresenta un file Excel XLAM
TSV Rappresenta un file con valori separati da tabulazioni
TAB_DELIMITED Rappresenta un file di testo delimitato da tabulazioni
HTML Rappresenta un file HTML
M_HTML Rappresenta file MHTML
ODS Rappresenta un file di foglio di calcolo OpenDocument
EXCEL_97_TO_2003 Rappresenta un file XLS, formato predefinito per le revisioni di Excel dal 1997 al 2003
SPREADSHEET_ML Rappresenta un file SpreadSheetML
XLSB Rappresenta un file XLSB binario di Excel 2007
UNKNOWN Rappresenta un formato non riconosciuto, non può essere salvato
PDF Rappresenta un documento PDF
XPS Rappresenta un file XML Paper Specification (XPS)
TIFF Rappresenta un file Tagged Image File Format (TIFF)
SVG Rappresenta un file basato su XML per Scalable Vector Graphics (SVG)
DIF Rappresenta un formato di scambio dati
NUMBERS Rappresenta un file di numeri
MARKDOWN Rappresenta un documento di markdown
Normalmente, ci sono due modi per salvare i file Excel come segue:
  1. Salvare il file in una determinata posizione
  2. Salvare il file in uno stream

Salvataggio del file in una determinata posizione

Se gli sviluppatori devono salvare i propri file in qualche posizione di archiviazione, possono semplicemente specificare il nome del file (con il relativo percorso di archiviazione completo) e il formato desiderato del file (usando l’enumerazione SaveFormat) durante la chiamata del metodo save dell’oggetto Workbook

Esempio:

// 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(SavingFiletoSomeLocation.class) + "loading_saving/";
String filePath = dataDir + "Book1.xls";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook(filePath);
// Save in Excel 97 – 2003 format
workbook.save(dataDir + "SFTSomeLocation_out.xls");
// OR
// workbook.save(dataDir + ".output..xls", new
// XlsSaveOptions(SaveFormat.Excel97To2003));
// Save in Excel2007 xlsx format
workbook.save(dataDir + "SFTSomeLocation_out.xlsx", FileFormatType.XLSX);
// Save in Excel2007 xlsb format
workbook.save(dataDir + "SFTSomeLocation_out.xlsb", FileFormatType.XLSB);
// Save in ODS format
workbook.save(dataDir + "SFTSomeLocation_out.ods", FileFormatType.ODS);
// Save in Pdf format
workbook.save(dataDir + "SFTSomeLocation_out.pdf", FileFormatType.PDF);
// Save in Html format
workbook.save(dataDir + "SFTSomeLocation_out.html", FileFormatType.HTML);
// Save in SpreadsheetML format
workbook.save(dataDir + "SFTSomeLocation_out.xml", FileFormatType.EXCEL_2003_XML);
// Print Message
System.out.println("Worksheets are saved successfully.");

Salvataggio Workbook in formato testo o CSV

A volte si desidera convertire o salvare un workbook con più fogli di lavoro in formato testo. Per i formati di testo (ad esempio TXT, TabDelim, CSV ecc.), sia Microsoft Excel che Aspose.Cells di default salvano solo i contenuti del foglio di lavoro attivo

L’esempio di codice seguente spiega come salvare un intero workbook in formato testo. Carica il workbook di origine che potrebbe essere un file di fogli di calcolo Microsoft Excel o OpenOffice (quindi XLS, XLSX, XLSM, XLSB, ODS e così via) con un qualsiasi numero di fogli di lavoro.

Quando il codice viene eseguito, converte i dati di tutti i fogli del workbook nel formato TXT

Puoi modificare lo stesso esempio per salvare il tuo file in CSV. Per default, TxtSaveOptions.Separator è una virgola, quindi non specificare un separatore se si salva nel formato CSV. Nota: Se stai utilizzando la versione di valutazione e anche se il parametro del metodo TxtSaveOptions.setExportAllSheets(boolean value) è impostato su true, il programma esporterà comunque solo un foglio di lavoro.

Esempio:

// 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(SaveWorkbookToTextCSVFormat.class) + "loading_saving/";
// Load your source workbook
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Text save options. You can use any type of separator
TxtSaveOptions opts = new TxtSaveOptions();
opts.setSeparator('\t');
opts.setExportAllSheets(true);
//Save entire workbook data into file
workbook.save(dataDir + "SWTTextCSVFormat-out.txt", opts);
// Print message
System.out.println("Excel to Text File Conversion performed successfully.");

Salvataggio file di testo con separatore personalizzato

I file di testo contengono dati del foglio di calcolo senza formattazione. Il file è una sorta di file di testo semplice che può avere alcuni delimitatori personalizzati tra i suoi dati.

// 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(SavingTextFilewithCustomSeparator.class) + "loading_saving/";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook(dataDir + "Book1.xlsx");
TxtSaveOptions toptions = new TxtSaveOptions();
// Specify the separator
toptions.setSeparator(';');
workbook.save(dataDir + "STFWCSeparator_out.csv");
// Print Message
System.out.println("Worksheets are saved successfully.");

Salvataggio file in uno stream

Se gli sviluppatori devono salvare i propri file su uno Stream allora dovrebbero creare un oggetto FileOutputStream e salvare il file in tale oggetto Stream chiamando il metodo save dell’oggetto Workbook. Gli sviluppatori possono anche specificare il formato desiderato del file (usando l’enumerazione SaveFormat) durante la chiamata del metodo save

Esempio:

// 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(SavingFiletoStream.class) + "loading_saving/";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook(dataDir + "Book1.xlsx");
FileOutputStream stream = new FileOutputStream(dataDir + "SFToStream_out.xlsx");
workbook.save(stream, FileFormatType.XLSX);
// Print Message
System.out.println("Worksheets are saved successfully.");
stream.close();

Salvataggio file in altro formato

File XLS

// 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(SaveXLSFile.class) + "loading_saving/";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook();
// Save in xls format
workbook.save(dataDir + "SXLSFile_out.xls", FileFormatType.EXCEL_97_TO_2003);
// Print Message
System.out.println("Worksheets are saved successfully.");

File XLSX

// 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(SaveXLSXFile.class) + "loading_saving/";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook();
// Save in xlsx format
workbook.save(dataDir + "SXLSXFile_out.xlsx", FileFormatType.XLSX);
// Print Message
System.out.println("Worksheets are saved successfully.");

File PDF

// 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(SaveInPdfFormat.class) + "loading_saving/";
// Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook();
// Save in PDF format
workbook.save(dataDir + "SIPdfFormat_out.pdf", FileFormatType.PDF);
// Print Message
System.out.println("Worksheets are saved successfully.");

Imposta l’opzione ContentCopyForAccessibility

Con la classe PdfSaveOptions, puoi ottenere o impostare l’opzione PDF AccessibilityExtractContent per controllare l’accesso al contenuto nel PDF convertito. Significa che consente al software screen reader di utilizzare il testo all’interno del file PDF per leggere il file PDF. Puoi disabilitarlo applicando una password di modifiche ai permessi e deselezionando i due elementi nello screenshot qui

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load excel file containing some data
Workbook workbook = new Workbook("book1.xlsx");
// Create an instance of PdfSaveOptions and pass SaveFormat to the constructor
PdfSaveOptions pdfSaveOpt = new PdfSaveOptions(SaveFormat.PDF);
// Create an instance of PdfSecurityOptions
PdfSecurityOptions securityOptions = new PdfSecurityOptions();
// Set AccessibilityExtractContent to true
securityOptions.setAccessibilityExtractContent(false);
// Set the securityoption in the PdfSaveOptions
pdfSaveOpt.setSecurityOptions(securityOptions);
// Save the workbook to PDF format while passing the object of PdfSaveOptions
workbook.save("outFile.pdf", pdfSaveOpt);

Esporta le proprietà personalizzate in PDF

Con la classe PdfSaveOptions, puoi esportare le proprietà personalizzate nel workbook di origine nel PDF. Viene fornita l’enumerazione PdfCustomPropertiesExport per specificare il modo con cui le proprietà vengono esportate. Queste proprietà possono essere visualizzate in Adobe Acrobat Reader cliccando su File e quindi sull’opzione delle proprietà come mostrato nell’immagine seguente. Il file modello “sourceWithCustProps.xlsx” può essere scaricato qui per il testing e il file PDF di output “outSourceWithCustProps” è disponibile qui per l’analisi

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load excel file containing custom properties
Workbook workbook = new Workbook("sourceWithCustProps.xlsx");
// Create an instance of PdfSaveOptions and pass SaveFormat to the constructor
PdfSaveOptions pdfSaveOpt = new PdfSaveOptions(SaveFormat.PDF);
// Set CustomPropertiesExport property to PdfCustomPropertiesExport.Standard
pdfSaveOpt.setCustomPropertiesExport(PdfCustomPropertiesExport.STANDARD);
// Save the workbook to PDF format while passing the object of PdfSaveOptions
workbook.save("outSourceWithCustProps.pdf", pdfSaveOpt);

Converti Workbook Excel in Markdown

L’API di Aspose.Cells fornisce il supporto per esportare i fogli di calcolo in formato Markdown. Per esportare il foglio di lavoro attivo in Markdown, passa SaveFormat.Markdown come secondo parametro del metodo Workbook.Save. Puoi anche usare la classe MarkdownSaveOptions per specificare impostazioni aggiuntive per esportare il foglio di lavoro in Markdown

L’esempio di codice seguente dimostra l’esportazione del foglio di lavoro attivo in Markdown utilizzando il membro di enumerazione SaveFormat.Markdown. Si prega di consultare il file Markdown di output generato dal codice per riferimento.

// 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(ConvertExcelFileToMarkdown.class) + "LoadingSavingConvertingAndManaging/";
Workbook workbook = new Workbook(dataDir + "Book1.xls");
// Save as Markdown
workbook.save(dataDir + "Book1.md", SaveFormat.MARKDOWN);

Argomenti avanzati