poi leer insertar exportar escribir desde descargar datos crear archivo java excel

insertar - leer excel xlsx desde java



Cómo leer y escribir el archivo de Excel (18)

Quiero leer y escribir un archivo Excel de Java con 3 columnas y N filas, imprimiendo una cadena en cada celda. ¿Alguien puede darme un fragmento de código simple para esto? ¿Debo usar cualquier lib externa o Java tiene soporte integrado para ella?

Quiero hacer lo siguiente:

for(i=0; i <rows; i++) //read [i,col1] ,[i,col2], [i,col3] for(i=0; i<rows; i++) //write [i,col1], [i,col2], [i,col3]


.csv o POI sin duda lo harán, pero debe conocer el JExcelApi de Andy Khan. Creo que es, de lejos, la mejor biblioteca de Java para trabajar con Excel.


Edité la más votada un poco porque no contaba los espacios en blanco de las columnas o las filas, no del todo, así que aquí está mi código, lo probé y ahora puedo obtener cualquier celda en cualquier parte de un archivo de Excel. también ahora puede tener columnas en blanco entre la columna llena y las leerá

try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row; HSSFCell cell; int rows; // No of rows rows = sheet.getPhysicalNumberOfRows(); int cols = 0; // No of columns int tmp = 0; int cblacks=0; // This trick ensures that we get the data properly even if it doesn''t start from first few rows for(int i = 0; i <= 10 || i <= rows; i++) { row = sheet.getRow(i); if(row != null) { tmp = sheet.getRow(i).getPhysicalNumberOfCells(); if(tmp >= cols) cols = tmp;else{rows++;cblacks++;} } cols++; } cols=cols+cblacks; for(int r = 0; r < rows; r++) { row = sheet.getRow(r); if(row != null) { for(int c = 0; c < cols; c++) { cell = row.getCell(c); if(cell != null) { System.out.print(cell+"/n");//Your Code here } } } }} catch(Exception ioe) { ioe.printStackTrace();}


Esto escribirá una JTable en un archivo separado por tabulaciones que se puede importar fácilmente a Excel. Esto funciona.

Si guarda una hoja de cálculo de Excel como un documento XML, también podría compilar el archivo XML para EXCEL con código. He hecho esto con la palabra para que no tengas que usar paquetes de terceros.

Esto podría hacer que se elimine la JTable y luego simplemente escribir una pestaña separada de cualquier archivo de texto y luego importar a Excel. Espero que esto ayude.

Código:

import java.io.File; import java.io.FileWriter; import java.io.IOException; import javax.swing.JTable; import javax.swing.table.TableModel; public class excel { String columnNames[] = { "Column 1", "Column 2", "Column 3" }; // Create some data String dataValues[][] = { { "12", "234", "67" }, { "-123", "43", "853" }, { "93", "89.2", "109" }, { "279", "9033", "3092" } }; JTable table; excel() { table = new JTable( dataValues, columnNames ); } public void toExcel(JTable table, File file){ try{ TableModel model = table.getModel(); FileWriter excel = new FileWriter(file); for(int i = 0; i < model.getColumnCount(); i++){ excel.write(model.getColumnName(i) + "/t"); } excel.write("/n"); for(int i=0; i< model.getRowCount(); i++) { for(int j=0; j < model.getColumnCount(); j++) { excel.write(model.getValueAt(i,j).toString()+"/t"); } excel.write("/n"); } excel.close(); }catch(IOException e){ System.out.println(e); } } public static void main(String[] o) { excel cv = new excel(); cv.toExcel(cv.table,new File("C://Users//itpr13266//Desktop//cs.tbv")); } }


Hay una nueva herramienta fácil y muy buena (10x a Kfir): xcelite

Escribir:

public class User { @Column (name="Firstname") private String firstName; @Column (name="Lastname") private String lastName; @Column private long id; @Column private Date birthDate; } Xcelite xcelite = new Xcelite(); XceliteSheet sheet = xcelite.createSheet("users"); SheetWriter<User> writer = sheet.getBeanWriter(User.class); List<User> users = new ArrayList<User>(); // ...fill up users writer.write(users); xcelite.write(new File("users_doc.xlsx"));

Leer:

Xcelite xcelite = new Xcelite(new File("users_doc.xlsx")); XceliteSheet sheet = xcelite.getSheet("users"); SheetReader<User> reader = sheet.getBeanReader(User.class); Collection<User> users = reader.read();


Otra forma de leer / escribir archivos de Excel es usar Windmill . Proporciona una API fluida para procesar archivos de Excel y CSV.

Datos de importacion

try (Stream<Row> rowStream = Windmill.parse(FileSource.of(new FileInputStream("myFile.xlsx")))) { rowStream // skip the header row that contains the column names .skip(1) .forEach(row -> { System.out.println( "row n°" + row.rowIndex() + " column ''User login'' value : " + row.cell("User login").asString() + " column n°3 number value : " + row.cell(2).asDouble().value() // index is zero-based ); }); }

Exportar datos

Windmill .export(Arrays.asList(bean1, bean2, bean3)) .withHeaderMapping( new ExportHeaderMapping<Bean>() .add("Name", Bean::getName) .add("User login", bean -> bean.getUser().getLogin()) ) .asExcel() .writeTo(new FileOutputStream("Export.xlsx"));


Para leer datos de libros de ejercicios .xlsx, necesitamos usar clases de XSSFworkbook.

XSSFWorkbook xlsxBook = new XSSFWorkbook(fis);

XSSFSheet sheet = xlsxBook.getSheetAt(0); etc.

Necesitamos usar Apache-poi 3.9 @ http://poi.apache.org/

Para obtener información detallada con el ejemplo, visite: http://java-recent.blogspot.in


Para leer un archivo xlsx podemos usar libs de POI de Apache Pruebe esto:

public static void readXLSXFile() throws IOException { InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); XSSFWorkbook test = new XSSFWorkbook(); XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row; XSSFCell cell; Iterator rows = sheet.rowIterator(); while (rows.hasNext()) { row=(XSSFRow) rows.next(); Iterator cells = row.cellIterator(); while (cells.hasNext()) { cell=(XSSFCell) cells.next(); if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) { System.out.print(cell.getStringCellValue()+" "); } else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { System.out.print(cell.getNumericCellValue()+" "); } else { //U Can Handel Boolean, Formula, Errors } } System.out.println(); } }


Primero agregue todos estos archivos jar en su ruta de clase de proyecto:

  1. poi-scratchpad-3.7-20101029
  2. poi-3.2-FINAL-20081019
  3. poi-3.7-20101029
  4. poi-examples-3.7-20101029
  5. poi-ooxml-3.7-20101029
  6. poi-ooxml-schemas-3.7-20101029
  7. xmlbeans-2.3.0
  8. dom4j-1.6.1

Código para escribir en un archivo de Excel:

public static void main(String[] args) { //Blank workbook XSSFWorkbook workbook = new XSSFWorkbook(); //Create a blank sheet XSSFSheet sheet = workbook.createSheet("Employee Data"); //This data needs to be written (Object[]) Map<String, Object[]> data = new TreeMap<String, Object[]>(); data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); data.put("2", new Object[]{1, "Amit", "Shukla"}); data.put("3", new Object[]{2, "Lokesh", "Gupta"}); data.put("4", new Object[]{3, "John", "Adwards"}); data.put("5", new Object[]{4, "Brian", "Schultz"}); //Iterate over data and write to sheet Set<String> keyset = data.keySet(); int rownum = 0; for (String key : keyset) { //create a row of excelsheet Row row = sheet.createRow(rownum++); //get object array of prerticuler key Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) { cell.setCellValue((String) obj); } else if (obj instanceof Integer) { cell.setCellValue((Integer) obj); } } } try { //Write the workbook in file system FileOutputStream out = new FileOutputStream(new File("C://Documents and Settings//admin//Desktop//imp data//howtodoinjava_demo.xlsx")); workbook.write(out); out.close(); System.out.println("howtodoinjava_demo.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } }

Código para leer desde el archivo de Excel

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("C://Documents and Settings//admin//Desktop//imp data//howtodoinjava_demo.xlsx")); //Create Workbook instance holding reference to .xlsx file XSSFWorkbook workbook = new XSSFWorkbook(file); //Get first/desired sheet from the workbook XSSFSheet sheet = workbook.getSheetAt(0); //Iterate through each rows one by one Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); //For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); //Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "/t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "/t"); break; } } System.out.println(""); } file.close(); } catch (Exception e) { e.printStackTrace(); } }


Pruebe el POI de Apache HSSF . Aquí hay un ejemplo de cómo leer un archivo de Excel:

try { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row; HSSFCell cell; int rows; // No of rows rows = sheet.getPhysicalNumberOfRows(); int cols = 0; // No of columns int tmp = 0; // This trick ensures that we get the data properly even if it doesn''t start from first few rows for(int i = 0; i < 10 || i < rows; i++) { row = sheet.getRow(i); if(row != null) { tmp = sheet.getRow(i).getPhysicalNumberOfCells(); if(tmp > cols) cols = tmp; } } for(int r = 0; r < rows; r++) { row = sheet.getRow(r); if(row != null) { for(int c = 0; c < cols; c++) { cell = row.getCell((short)c); if(cell != null) { // Your code here } } } } } catch(Exception ioe) { ioe.printStackTrace(); }

En la página de documentación también tiene ejemplos de cómo escribir en archivos de Excel.


Seguro, encontrará que el siguiente código es útil y fácil de leer y escribir. Esta es una clase de utilidades que puede usar en su método principal y luego es bueno usar todos los métodos a continuación.

public class ExcelUtils { private static XSSFSheet ExcelWSheet; private static XSSFWorkbook ExcelWBook; private static XSSFCell Cell; private static XSSFRow Row; File fileName = new File("C://Users//satekuma//Pro//Fund.xlsx"); public void setExcelFile(File Path, String SheetName) throws Exception try { FileInputStream ExcelFile = new FileInputStream(Path); ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); } catch (Exception e) { throw (e); } } public static String getCellData(int RowNum, int ColNum) throws Exception { try { Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum); String CellData = Cell.getStringCellValue(); return CellData; } catch (Exception e) { return ""; } } public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception { try { Row = ExcelWSheet.createRow(RowNum - 1); Cell = Row.createCell(ColNum - 1); Cell.setCellValue(Result); FileOutputStream fileOut = new FileOutputStream(Path); ExcelWBook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (Exception e) { throw (e); } } }


Si el número de columna varía, puede usar esto

package com.org.tests; import org.apache.poi.xssf.usermodel.*; import java.io.FileInputStream; import java.io.IOException; public class ExcelSimpleTest { String path; public FileInputStream fis = null; private XSSFWorkbook workbook = null; private XSSFSheet sheet = null; private XSSFRow row =null; private XSSFCell cell = null; public ExcelSimpleTest() throws IOException { path = System.getProperty("user.dir")+"//resources//Book1.xlsx"; fis = new FileInputStream(path); workbook = new XSSFWorkbook(fis); sheet = workbook.getSheetAt(0); } public void ExelWorks() { int index = workbook.getSheetIndex("Sheet1"); sheet = workbook.getSheetAt(index); int rownumber=sheet.getLastRowNum()+1; for (int i=1; i<rownumber; i++ ) { row = sheet.getRow(i); int colnumber = row.getLastCellNum(); for (int j=0; j<colnumber; j++ ) { cell = row.getCell(j); System.out.println(cell.getStringCellValue()); } } } public static void main(String[] args) throws IOException { ExcelSimpleTest excelwork = new ExcelSimpleTest(); excelwork.ExelWorks(); } }

El mavendependency correspondiente se puede encontrar here


Si necesita hacer algo más con documentos de Office en Java, vaya a POI como se menciona.

Para leer / escribir de forma sencilla un documento de Excel como el que solicitó, puede usar el formato CSV (también como se menciona):

import java.io.BufferedReader; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class CsvWriter { public static void main(String args[]) throws IOException { String fileName = "test.xls"; PrintWriter out = new PrintWriter(new FileWriter(fileName)); out.println("a,b,c,d"); out.println("e,f,g,h"); out.println("i,j,k,l"); out.close(); BufferedReader in = new BufferedReader(new FileReader(fileName)); String line = null; while ((line = in.readLine()) != null) { Scanner scanner = new Scanner(line); String sep = ""; while (scanner.hasNext()) { System.out.println(sep + scanner.next()); sep = ","; } } in.close(); } }


También puede considerar JExcelApi . Lo encuentro mejor diseñado que POI. Hay un tutorial here .


Un simple archivo CSV debería ser suficiente


Utilice las libs de POI de Apache e intente esto.

public class TakingDataFromExcel { public static void main(String[] args) { try { FileInputStream x = new FileInputStream(new File("/Users/rajesh/Documents/rajesh.xls")); //Create Workbook instance holding reference to .xlsx file Workbook workbook = new HSSFWorkbook(x); //Get first/desired sheet from the workbook Sheet sheet = workbook.getSheetAt(0); //Iterate through each rows one by one for (Iterator<Row> iterator = sheet.iterator(); iterator.hasNext();) { Row row = (Row) iterator.next(); for (Iterator<Cell> iterator2 = row.iterator(); iterator2 .hasNext();) { Cell cell = (Cell) iterator2.next(); System.out.println(cell.getStringCellValue()); } } x.close(); } catch (Exception e) { e.printStackTrace(); } } }


usando primavera apache poi repo

if (fileName.endsWith(".xls")) { File myFile = new File("file location" + fileName); FileInputStream fis = new FileInputStream(myFile); org.apache.poi.ss.usermodel.Workbook workbook = null; try { workbook = WorkbookFactory.create(fis); } catch (InvalidFormatException e) { e.printStackTrace(); } org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue()); break; } System.out.print(" - "); } System.out.println(); } }


Apache POI puede hacer esto por usted. Específicamente el módulo HSSF . La guía rápida es más útil. A continuación, le mostramos cómo hacer lo que desea, específicamente, crear una hoja y escribirla.

Workbook wb = new HSSFWorkbook(); //Workbook wb = new XSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("new sheet"); // Create a row and put some cells in it. Rows are 0 based. Row row = sheet.createRow((short)0); // Create a cell and put a value in it. Cell cell = row.createCell(0); cell.setCellValue(1); // Or do it on one line. row.createCell(1).setCellValue(1.2); row.createCell(2).setCellValue( createHelper.createRichTextString("This is a string")); row.createCell(3).setCellValue(true); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close();


String path="C://Book2.xlsx"; try { File f = new File( path ); Workbook wb = WorkbookFactory.create(f); Sheet mySheet = wb.getSheetAt(0); Iterator<Row> rowIter = mySheet.rowIterator(); for ( Iterator<Row> rowIterator = mySheet.rowIterator() ;rowIterator.hasNext(); ) { for ( Iterator<Cell> cellIterator = ((Row)rowIterator.next()).cellIterator() ; cellIterator.hasNext() ; ) { System.out.println ( ( (Cell)cellIterator.next() ).toString() ); } System.out.println( " **************************************************************** "); } } catch ( Exception e ) { System.out.println( "exception" ); e.printStackTrace(); }

y asegúrese de haber agregado los archivos jar poi y poi-ooxml (org.apache.poi) a su proyecto