Java'dan 3 sütunlu ve N satırlı bir Excel dosyasını okumak ve yazmak, her hücreye bir dize yazdırmak istiyorum. Bunun için bana basit bir kod parçacığı verebilecek olan var mı? Herhangi bir harici lib kullanmam gerekiyor mu yoksa Java'nın bunun için yerleşik desteği var mı?
Aşağıdakileri yapmak istiyorum:
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]
Apache POI HSSF]1'i deneyin. İşte bir excel dosyasının nasıl okunacağına dair bir örnek:
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();
}
Dokümantasyon sayfasında excel dosyalarına nasıl yazılacağına dair örnekler de var.
Apache POI bunu sizin için yapabilir. Özellikle HSSF modülü. Hızlı kılavuz]3 en yararlı olanıdır. İstediğiniz şeyi nasıl yapacağınız aşağıda açıklanmıştır - özellikle bir sayfa oluşturun ve yazın.
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();