Utilizzo dell API LightCells
Architettura basata su eventi
Aspose.Cells fornisce la LightCells API, progettata principalmente per manipolare i dati delle celle uno per uno senza costruire un blocco di modello di dati completo (utilizzando la collezione di celle ecc.) in memoria. Funziona in modalità basata su eventi.
Per salvare i workbook, fornisci il contenuto della cella cella per cella durante il salvataggio e il componente lo salva direttamente nel file di output.
Quando si leggono file di template, il componente analizza ogni cella e fornisce il loro valore uno per uno.
In entrambe le procedure, un oggetto Cell viene elaborato e quindi scartato, l’oggetto Workbook non detiene la collezione. In questa modalità, quindi, si risparmia memoria durante l’importazione ed esportazione di un file Microsoft Excel che ha un ampio set di dati che altrimenti utilizzerebbe molta memoria.
Anche se la LightCells API elabora le celle allo stesso modo per i file XLSX e XLS (non carica effettivamente tutte le celle in memoria ma elabora una cella e poi la scarta), salva la memoria in modo più efficace per i file XLSX rispetto ai file XLS a causa dei diversi modelli di dati e delle strutture dei due formati.
Tuttavia, per i file XLS, per risparmiare memoria, gli sviluppatori possono specificare una posizione temporanea per salvare i dati temporanei generati durante il processo di salvataggio. Comunemente, utilizzando LightCells API per salvare i file XLSX può risparmiare il 50% o più di memoria rispetto al metodo comune, salvare i file XLS può risparmiare circa il 20-40% di memoria.
Scrittura di file Excel di grandi dimensioni
Aspose.Cells fornisce un’interfaccia, LightCellsDataProvider, che deve essere implementata nel tuo programma. L’interfaccia rappresenta il provider dei dati per salvare grandi file di fogli di calcolo in modalità leggera.
Quando si salva un workbook in questa modalità, startSheet(int) viene controllato quando si salva ogni foglio di lavoro nell’workbook. Per un foglio, se startSheet(int) è true, all i dati e le proprietà delle righe e delle celle di questo foglio da salvare vengono forniti da questa implementazione. In primo luogo, nextRow() viene chiamato per ottenere l’indice della prossima riga da salvare. Se viene restituito un indice di riga valido (l’indice di riga deve essere in ordine crescente per le righe da salvare), viene fornito un oggetto Row che rappresenta questa riga per l’implementazione per impostare le sue proprietà con startRow(Row).
Per una riga, verrà prima controllato nextCell(). Se viene restituito un indice di colonna valido (l’indice di colonna deve essere in ordine crescente per tutte le celle di una riga da salvare), viene fornito un oggetto Cell che rappresenta questa cella per impostare i dati e le proprietà con startCell(Cell). Dopo che i dati di questa cella sono impostati, questa cella viene salvata direttamente nel file di fogli di calcolo generato e verrà controllata e elaborata la prossima cella.
L’esempio seguente mostra come funziona l’API LightCells.
Il seguente programma crea un file enorme con 100.000 record in un foglio di lavoro, riempito con dati. Abbiamo aggiunto alcuni collegamenti ipertestuali, valori di stringhe, valori numerici e anche formule a determinate celle nel foglio di lavoro. Inoltre, abbiamo formattato un intervallo di celle.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class LightCellsDataProviderDemo implements LightCellsDataProvider { | |
private final int sheetCount; | |
private final int maxRowIndex; | |
private final int maxColIndex; | |
private int rowIndex; | |
private int colIndex; | |
private final Style style1; | |
private final Style style2; | |
public LightCellsDataProviderDemo(Workbook wb, int sheetCount, int rowCount, int colCount) { | |
// set the variables/objects | |
this.sheetCount = sheetCount; | |
this.maxRowIndex = rowCount - 1; | |
this.maxColIndex = colCount - 1; | |
// add new style object with specific formattings | |
style1 = wb.createStyle(); | |
Font font = style1.getFont(); | |
font.setName("MS Sans Serif"); | |
font.setSize(10); | |
font.setBold(true); | |
font.setItalic(true); | |
font.setUnderline(FontUnderlineType.SINGLE); | |
font.setColor(Color.fromArgb(0xffff0000)); | |
style1.setHorizontalAlignment(TextAlignmentType.CENTER); | |
// create another style | |
style2 = wb.createStyle(); | |
style2.setCustom("#,##0.00"); | |
font = style2.getFont(); | |
font.setName("Copperplate Gothic Bold"); | |
font.setSize(8); | |
style2.setPattern(BackgroundType.SOLID); | |
style2.setForegroundColor(Color.fromArgb(0xff0000ff)); | |
style2.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, Color.getBlack()); | |
style2.setVerticalAlignment(TextAlignmentType.CENTER); | |
} | |
public boolean isGatherString() { | |
return false; | |
} | |
public int nextCell() { | |
if (colIndex < maxColIndex) { | |
colIndex++; | |
return colIndex; | |
} | |
return -1; | |
} | |
public int nextRow() { | |
if (rowIndex < maxRowIndex) { | |
rowIndex++; | |
colIndex = -1; // reset column index | |
if (rowIndex % 1000 == 0) { | |
System.out.println("Row " + rowIndex); | |
} | |
return rowIndex; | |
} | |
return -1; | |
} | |
public void startCell(Cell cell) { | |
if (rowIndex % 50 == 0 && (colIndex == 0 || colIndex == 3)) { | |
// do not change the content of hyperlink. | |
return; | |
} | |
if (colIndex < 10) { | |
cell.putValue("test_" + rowIndex + "_" + colIndex); | |
cell.setStyle(style1); | |
} else { | |
if (colIndex == 19) { | |
cell.setFormula("=Rand() + test!L1"); | |
} else { | |
cell.putValue(rowIndex * colIndex); | |
} | |
cell.setStyle(style2); | |
} | |
} | |
public void startRow(Row row) { | |
row.setHeight(25); | |
} | |
public boolean startSheet(int sheetIndex) { | |
if (sheetIndex < sheetCount) { | |
// reset row/column index | |
rowIndex = -1; | |
colIndex = -1; | |
return true; | |
} | |
return false; | |
} | |
} |
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class Demo { | |
private static final String OUTPUT_FILE_PATH = Utils.getDataDir(LightCellsDataProviderDemo.class); | |
public static void main(String[] args) throws Exception { | |
// Instantiate a new Workbook | |
Workbook wb = new Workbook(); | |
// set the sheet count | |
int sheetCount = 1; | |
// set the number of rows for the big matrix | |
int rowCount = 100000; | |
// specify the worksheet | |
for (int k = 0; k < sheetCount; k++) { | |
Worksheet sheet = null; | |
if (k == 0) { | |
sheet = wb.getWorksheets().get(k); | |
sheet.setName("test"); | |
} else { | |
int sheetIndex = wb.getWorksheets().add(); | |
sheet = wb.getWorksheets().get(sheetIndex); | |
sheet.setName("test" + sheetIndex); | |
} | |
Cells cells = sheet.getCells(); | |
// set the columns width | |
for (int j = 0; j < 15; j++) { | |
cells.setColumnWidth(j, 15); | |
} | |
// traverse the columns for adding hyperlinks and merging | |
for (int i = 0; i < rowCount; i++) { | |
// The first 10 columns | |
for (int j = 0; j < 10; j++) { | |
if (j % 3 == 0) { | |
cells.merge(i, j, 1, 2, false, false); | |
} | |
if (i % 50 == 0) { | |
if (j == 0) { | |
sheet.getHyperlinks().add(i, j, 1, 1, "test!A1"); | |
} else if (j == 3) { | |
sheet.getHyperlinks().add(i, j, 1, 1, "http://www.google.com"); | |
} | |
} | |
} | |
// The second 10 columns | |
for (int j = 10; j < 20; j++) { | |
if (j == 12) { | |
cells.merge(i, j, 1, 3, false, false); | |
} | |
} | |
} | |
} | |
// Create an object with respect to LightCells data provider | |
LightCellsDataProviderDemo dataProvider = new LightCellsDataProviderDemo(wb, 1, rowCount, 20); | |
// Specify the XLSX file's Save options | |
OoxmlSaveOptions opt = new OoxmlSaveOptions(); | |
// Set the data provider for the file | |
opt.setLightCellsDataProvider(dataProvider); | |
// Save the big file | |
wb.save(OUTPUT_FILE_PATH + "/DemoTest.xlsx", opt); | |
} | |
} |
Lettura di File Excel di Grandi Dimensioni
Aspose.Cells fornisce un’interfaccia, LightCellsDataHandler, che deve essere implementata nel tuo programma. L’interfaccia rappresenta il provider dei dati per leggere grandi file di fogli di calcolo in modalità leggera.
Quando si legge un workbook in questa modalità, viene controllato startSheet() quando si legge ogni foglio di lavoro nell’workbook. Per un foglio, se startSheet() restituisce true, all i dati e le proprietà delle celle nelle righe e nelle colonne del foglio vengono controllati ed elaborati. Per ogni riga, viene chiamato startRow() per controllare se deve essere elaborata. Se una riga deve essere elaborata, le proprietà della riga vengono lette prima e gli sviluppatori possono accedere alle sue proprietà con processRow().
Se le celle della riga devono anche essere elaborate, allora processRow() restituisce true e per ogni cella esistente nella riga viene chiamato startCell() per controllare se deve essere elaborata. Se lo fa, viene chiamato processCell().
Il seguente codice di esempio illustra questo processo. Il programma legge un file grande con milioni di record. Richiede un po' di tempo per leggere ogni foglio di lavoro nell’workbook. Il codice di esempio legge il file e recupera il numero totale di celle, contatori di stringhe e conteggi di formule per ogni foglio di lavoro.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class LightCellsTest1 { | |
public static void main(String[] args) throws Exception { | |
String dataDir = Utils.getDataDir(LightCellsTest1.class); | |
LoadOptions opts = new LoadOptions(); | |
LightCellsDataHandlerVisitCells v = new LightCellsDataHandlerVisitCells(); | |
opts.setLightCellsDataHandler((LightCellsDataHandler) v); | |
Workbook wb = new Workbook(dataDir + "LargeBook1.xlsx", opts); | |
int sheetCount = wb.getWorksheets().getCount(); | |
System.out.println("Total sheets: " + sheetCount + ", cells: " + v.cellCount + ", strings: " + v.stringCount | |
+ ", formulas: " + v.formulaCount); | |
} | |
} |
Una classe che implementa l’interfaccia LightCellsDataHandler
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
public class LightCellsDataHandlerVisitCells implements LightCellsDataHandler { | |
public int cellCount; | |
public int formulaCount; | |
public int stringCount; | |
public LightCellsDataHandlerVisitCells() { | |
this.cellCount = 0; | |
this.formulaCount = 0; | |
this.stringCount = 0; | |
} | |
public int cellCount() { | |
return cellCount; | |
} | |
public int formulaCount() { | |
return formulaCount; | |
} | |
public int stringCount() { | |
return stringCount; | |
} | |
public boolean startSheet(Worksheet sheet) { | |
System.out.println("Processing sheet[" + sheet.getName() + "]"); | |
return true; | |
} | |
public boolean startRow(int rowIndex) { | |
return true; | |
} | |
public boolean processRow(Row row) { | |
return true; | |
} | |
public boolean startCell(int column) { | |
return true; | |
} | |
public boolean processCell(Cell cell) { | |
this.cellCount = this.cellCount + 1; | |
if (cell.isFormula()) { | |
this.formulaCount = this.formulaCount + 1; | |
} else if (cell.getType() == CellValueType.IS_STRING) { | |
this.stringCount = this.stringCount + 1; | |
} | |
return false; | |
} | |
} |