importjava.io.File;importjava.io.IOException;importjxl.Workbook;importjxl.write.Label;importjxl.write.WritableSheet;importjxl.write.WritableWorkbook;importjxl.write.WriteException;importjxl.Sheet;importjxl.read.biff.BiffException;importorg.springframework.stereotype.Component;
@Componentpublic classExcelByJxl {public static voidwriteExcelByJxl(String path) {try{
File xlsFile= newFile(path);//创建一个工作簿
WritableWorkbook workbook =Workbook.createWorkbook(xlsFile);//创建一个工作表
WritableSheet sheet = workbook.createSheet("sheet1", 0);for (int row = 0; row < 10; row++)
{for (int col = 0; col < 10; col++)
{//向工作表中添加数据
sheet.addCell(new Label(col, row, "data" + row +col));
}
}//创建一个工作表
WritableSheet sheet1 = workbook.createSheet("sheet2", 0);for (int row = 0; row < 10; row++)
{for (int col = 0; col < 10; col++)
{if(row == 0) {//添加表头
sheet1.addCell(new Label(0, 0, "班级"));
sheet1.addCell(new Label(1, 0, "姓名"));
sheet1.addCell(new Label(2, 0, "年级"));
sheet1.addCell(new Label(3, 0, "年龄"));
sheet1.addCell(new Label(4, 0, "生日"));
sheet1.addCell(new Label(5, 0, "住址"));
sheet1.addCell(new Label(6, 0, "性别"));
sheet1.addCell(new Label(7, 0, "爸爸"));
sheet1.addCell(new Label(8, 0, "妈妈"));
sheet1.addCell(new Label(9, 0, "班主任"));
}else{//向工作表中添加数据
sheet1.addCell(new Label(col, row, "data" + row +col));
}
}
}
workbook.write();
workbook.close();
}catch(IOException e) {
e.printStackTrace();
}catch(WriteException e) {
e.printStackTrace();
}
}public static voidreadExcelByJxl(String path) {try{
File xlsFile= newFile(path);//获得工作簿对象
Workbook workbook =Workbook.getWorkbook(xlsFile);//获得所有工作表
Sheet[] sheets =workbook.getSheets();//遍历工作表
if (sheets != null)
{for(Sheet sheet : sheets)
{//获得行数
int rows =sheet.getRows();//获得列数
int cols =sheet.getColumns();//读取数据
for (int row = 0; row < rows; row++)
{for (int col = 0; col < cols; col++)
{
System.out.printf("%10s", sheet.getCell(col, row)
.getContents());
}
System.out.println();
}
}
}
workbook.close();
}catch(IOException e) {
e.printStackTrace();
}catch(BiffException e) {
e.printStackTrace();
}
}
}