java如何创建excel表格并插入数据

1、需要的jar包


2、java代码

(1) 创建xxx.xlsx文件,及2007版本

package com.gl;

import java.io.FileOutputStream;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class WriteExcel {

public WriteExcel() {
}
public static void main(String[] args) {
WriteExcel we = new WriteExcel();
we.insertRecord("G:\\workbook2.xlsx");
}
public void insertRecord(String filePath){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("名单");
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue("花名册");
//合并单元格CellRangeAddress构造参数一次表示起始行,截止行,起始列,截止列
sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));

XSSFRow row2 = sheet.createRow(1);
row2.createCell(0).setCellValue("姓名");
row2.createCell(1).setCellValue("班级");
row2.createCell(2).setCellValue("成绩");

XSSFRow row3 = sheet.createRow(2);
row3.createCell(0).setCellValue("王若冰");
row3.createCell(1).setCellValue("a-1");
row3.createCell(2).setCellValue("89");
try {
FileOutputStream output = new FileOutputStream(filePath);
wb.write(output);
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}


(2) 创建xxx.xls文件,及2003版本

package com.gl;

import java.io.FileOutputStream;

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;
import org.apache.poi.ss.util.CellRangeAddress;

public class WriteExcel2 {

public WriteExcel2() {
}
public static void main(String[] args) {
WriteExcel2 we = new WriteExcel2();
we.insertRecord("G:\\workbook2.xls");
}
public void insertRecord(String filePath){
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("名单");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue("花名册");
//合并单元格CellRangeAddress构造参数一次表示起始行,截止行,起始列,截止列
sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));

HSSFRow row2 = sheet.createRow(1);
row2.createCell(0).setCellValue("姓名");
row2.createCell(1).setCellValue("班级");
row2.createCell(2).setCellValue("成绩");

HSSFRow row3 = sheet.createRow(2);
row3.createCell(0).setCellValue("王若冰");
row3.createCell(1).setCellValue("a-1");
row3.createCell(2).setCellValue("89");

try {
FileOutputStream output = new FileOutputStream(filePath);
wb.write(output);
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}















































































猜你喜欢

转载自blog.csdn.net/weixin_40480741/article/details/80340719