大家好,我是Java Poi库的新手,我想尽我所有的运气来学习这个库,但仍然没有运气
我想要这个输出
Excel1.xls有此数据
邮政编码|位置|日期
211
我想复制所有第一行数据。
邮政编码|位置|日期
放在另一张纸上
这是我编写的代码
public static void main(String[] args) throws IOException{
try {
FileInputStream file = new FileInputStream(new File("d:\\input.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFSheet zip1 = workbook.createSheet("ZIP CODE 1");
for(Row row : sheet){
int i=0;
for(Cell cell : row){
cell.setCellType(Cell.CELL_TYPE_STRING);
System.out.print(cell.getStringCellValue() + "\t");
String a = cell.getStringCellValue();
cell = zip1.createRow(i).createCell(i);
i++;
cell.setCellValue(a);
}
break;
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File("d:\\output.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
最佳答案
发现问题
对于.xlsx文件-> HSSFWorkbook
应为XSSFWorkbook
环。您不想循环只希望第一行的每一行。只是循环列
每次要写入单元格时不要创建行。仅创建一次新行。
工作示例:
try {
FileInputStream file = new FileInputStream(new File(
"C:\\path\\Book1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet zip1 = workbook.createSheet("ZIP CODE 1");
Row readFirstRow = sheet.getRow(0);
Row writeFirstRow = zip1.createRow(0);
for (Cell cell : readFirstRow) {
cell.setCellType(Cell.CELL_TYPE_STRING);
String a = cell.getStringCellValue();
cell = writeFirstRow.createCell(cell.getColumnIndex());
cell.setCellValue(a);
}
file.close();
FileOutputStream outFile = new FileOutputStream(new File(
"C:\\path\\BookOut.xlsx"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}