package exceltest;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import java.io.*;
public class ExcelTest {
public static String Filename = "test.xls";//文件存储在idea的workspace中
public static void main(String[] args) throws FileNotFoundException {
try {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet();
hssfWorkbook.setSheetName(0, "征信");//sheet页从0开始
for (int i = 0; i < 10; i++) {//10行
HSSFRow hssfRow = sheet.createRow(i);
for (int j = 0; j < 2; j++) {//2列
HSSFCell hssfCell = hssfRow.createCell(j);
if (j == 0) {
hssfCell.setCellType(CellType.STRING);
if (i == 0 & j == 0) {
hssfCell.setCellValue("姓名");
} else {
hssfCell.setCellValue("张三" + i);
}
} else if (i == 0 && j == 1) {
hssfCell.setCellType(CellType.STRING);
hssfCell.setCellValue("年龄");
} else {
hssfCell.setCellType(CellType.NUMERIC);
hssfCell.setCellValue(12 + i);
}
}
}
FileOutputStream fileOutputStream = new FileOutputStream(Filename);
hssfWorkbook.write(fileOutputStream);
fileOutputStream.flush();
FileInputStream fileInputStream = new FileInputStream(Filename);
HSSFWorkbook read = new HSSFWorkbook(fileInputStream);
HSSFSheet readsheet = read.getSheet("征信");
for (int k = 0; k <= sheet.getLastRowNum(); k++) {
HSSFRow readrow = readsheet.getRow(k);
for (int m = 0; m < readrow.getLastCellNum(); m++) {
HSSFCell readcell = readrow.getCell(m);
if (m==1&& k!=0) {
System.out.print(readcell.getNumericCellValue());
} else {
System.out.print(readcell.getStringCellValue()+" ");
}
if (m==1){
System.out.println();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
输出结果:
姓名 年龄
张三1 13.0
张三2 14.0
张三3 15.0
张三4 16.0
张三5 17.0
张三6 18.0
张三7 19.0
张三8 20.0
张三9 21.0