常见读取excel一般使用POI和JExcelAPI这两个库。
POI:
POI 下载处 http://poi.apache.org/
创建工作簿
// 07之前版本
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
// 07之后版本
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.close();
创建表单
Sheet sheet = wb.createSheet();
Sheet sheet = wb.createSheet("库存");
创建单元格 并设置值,可以是 String,int等类型
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("hello world");
package ask_test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class Excel { public static void createWorkBook() throws IOException { //创建excel工作簿 Workbook wb = new XSSFWorkbook(); //创建sheet(页) Sheet sheet1 = wb.createSheet("Sheet_1"); Sheet sheet2 = wb.createSheet("Sheet_2"); for( int i=0; i<20;i=i+2){ Row row1 = sheet1.createRow(i); Row row2 = sheet2.createRow(i); for (int j=0;j<10;j++){ // Or do it on one line. row1.createCell(j).setCellValue(j+"new"); row2.createCell(j).setCellValue(j+"This is a string"); } } //创建一个文件 命名为workbook.xlsx FileOutputStream fileOut = new FileOutputStream("F:\\workbooks.xlsx"); // 把上面创建的工作簿输出到文件中 wb.write(fileOut); //关闭输出流 fileOut.close(); } //使用POI读入excel工作簿文件 public static void readWorkBook() throws Exception { // poi读取excel //创建要读入的文件的输入流 InputStream inp = new FileInputStream("F:\\workbooks.xlsx"); //根据上述创建的输入流 创建工作簿对象 Workbook wb = WorkbookFactory.create(inp); //利用foreach循环 遍历sheet中的所有行 for (Sheet sheet: wb){ System.out.println(sheet.getSheetName()); for (Row row : sheet) { //遍历row中的所有方格 for (Cell cell : row) { //输出方格中的内容,以空格间隔 System.out.print(cell.toString() + " "); } //每一个行输出之后换行 System.out.println(); } } //关闭输入流 inp.close(); } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Excel.createWorkBook(); Excel.readWorkBook(); } }
时间: 2024-10-25 12:43:20