第一步:導入jar包
第二步:上代碼
package cn.lystudio.poi.excel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 生成excel文件
* @author Administrator
*
*/
public class PoiCExcel {
public static void main(String[] args) {
//創建一個數組,存放數據
String[] title = {"id","name","sex"};
//創建excel工作蒲
HSSFWorkbook workbook = new HSSFWorkbook();
//創建一個工作表sheet
HSSFSheet sheet = workbook.createSheet();
//創建第一行
HSSFRow row = sheet.createRow(0);
//定義cell
HSSFCell cell = null;
//插入第一行數據,id,name,sex
for ( int i =0; i<title.length;i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
}
//追加數據
for ( int i =1; i<10;i++) {
HSSFRow nextrow =sheet.createRow(i);
HSSFCell cell2 = nextrow.createCell(0);
cell2.setCellValue("a"+i);
cell2 = nextrow.createCell(1);
cell2.setCellValue("user"+i);
cell2 = nextrow.createCell(2);
cell2.setCellValue("女生");
}
//創建一個文件
File file = new File("D:/poi_test.xls");
try {
file.createNewFile();
//將excel內容存盤
FileOutputStream stream = FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}