Вопрос-ответ

How to read and write excel file

Как прочитать и записать файл Excel

Я хочу прочитать и записать файл Excel из Java с 3 столбцами и N строками, напечатав по одной строке в каждой ячейке. Кто-нибудь может дать мне простой фрагмент кода для этого? Нужно ли мне использовать какую-либо внешнюю библиотеку или в Java есть встроенная поддержка для нее?

Я хочу сделать следующее:

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]
Переведено автоматически
Ответ 1

Попробуйте Apache POI HSSF. Вот пример чтения файла 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();
}

На странице документации у вас также есть примеры записи в файлы Excel.

Ответ 2

Apache POI может сделать это за вас. В частности, модуль HSSF. Наиболее полезным является краткое руководство. Вот как сделать то, что вы хотите - в частности, создать лист и записать его.

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();
Ответ 3

Сначала добавьте все эти файлы jar в путь к классу вашего проекта:


  1. poi-scratchpad-3.7-20101029

  2. poi-3.2-FINAL-20081019

  3. poi-3.7-20101029

  4. poi-примеры-3.7-20101029

  5. poi-ooxml-3.7-20101029

  6. poi-ooxml-схемы-3.7-20101029

  7. xmlbeans-2.3.0

  8. dom4j-1.6.1

Код для записи в файл 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();
}
}

Код для чтения из файла 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();
}
}
Ответ 4

Вы также можете рассмотреть JExcelAPI. Я нахожу, что он разработан лучше, чем POI. Здесь есть руководство.

java