java向excel读写数据的步骤:
首先,需要jxl.jar包。
读excel文件:
public class Test2 {
public static void main(String[] args) {
try {
Workbook book = Workbook.getWorkbook(new File("测试.xls"));
// 获得第一个工作表对象
Sheet sheet = book.getSheet(0);
// 得到单元格
for (int i = 0; i < sheet.getColumns(); i++) {
for (int j = 0; j < sheet.getRows(); j++) {
Cell cell = sheet.getCell(i, j);
System.out.print(cell.getContents() + " ");
}
System.out.println();
}
book.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
向excel中写数据:
/**
* jxl 创xcel
*/
public void writerJXL() {
try {
long dir= (long) Math.round(Math.floor(Math.random() * 10000000));
String dirPath ="c://11//".concat(String.valueOf(dir)) ;
File file = new File(dirPath);
if(file.exists()) {
System.out.println(file.getName()+"存xl");
if(file.delete()) {
file.mkdir();
}
}else {
file.mkdir();
}
// 打
long l = (long) Math.round(Math.floor(Math.random() * 1000000000));
String name = "jxl_".concat(String.valueOf(l)).concat(".xls");
WritableWorkbook book = Workbook.createWorkbook( new File(dirPath.concat("//").concat(name)));
int j = 0 ;
while(j < sheet){ //控heet创
WritableSheet sheet = book.createSheet("test"+j ,j);
Label label1 = null ;
Label label2 = null ;
for(int i = 0 ; i < leng ;i ++){
label1 = new Label(0,i,"A数xl"+i ); //第第
label2 = new Label(1,i,"A数xl"+i );
sheet.addCell(label1); // 将
sheet.addCell(label2);
}
j++ ;
}
book.write();
book.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}