导出
public static void main(String[] args) throws Exception {
//创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 添加sheet页
XSSFSheet sheet = workbook.createSheet("用户列表");
// 添加数据行
XSSFRow row = sheet.createRow(0);
// 添加数据列cell
XSSFCell cellName = row.createCell(1);
cellName.setCellValue("姓名");
XSSFCell cellCity = row.createCell(2);
cellCity.setCellValue("城市");
XSSFRow row1 = sheet.createRow(1);
XSSFCell cellName1 = row1.createCell(1);
cellName1.setCellValue("张三");
XSSFCell cellCity1 = row1.createCell(2);
cellCity1.setCellValue("北京");
XSSFRow row2 = sheet.createRow(2);
XSSFCell cellName2 = row2.createCell(1);
cellName2.setCellValue("李四");
XSSFCell cellCity2 = row2.createCell(2);
cellCity2.setCellValue("上海");
//也可以使用循环来导入重复数据
for (int i = 0; i < 10; i++) {
XSSFRow rowi = sheet.createRow(i + 3);
XSSFCell cellNamei = rowi.createCell(1);
cellNamei.setCellValue("李" + (i + 3));
XSSFCell cellCityi = rowi.createCell(2);
cellCityi.setCellValue("上海" + (i + 3));
}
FileOutputStream out = new FileOutputStream(new File("D:\\itcast.xlsx"));
//通过输出流将内存中的Excel文件写入到磁盘上
workbook.write(out);
// 关闭资源
out.close();
workbook.close();
}
导入
private static void importExcel()throws Exception{
InputStream in = new FileInputStream("D:\\itcast.xlsx");
//基于文件的输入流创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook(in);
// 读取sheet页
XSSFSheet sheet = workbook.getSheetAt(0);
// 读取一行
XSSFRow row = sheet.getRow(0);
// 读取第一列
XSSFCell cellNameHead = row.getCell(1);
String nameHead = cellNameHead.getStringCellValue();
XSSFCell cellCityHead = row.getCell(2);
String cityHead = cellCityHead.getStringCellValue();
System.out.println(nameHead + ":" + cityHead);
//获取Sheet页中的最后一行的行号
int lastRowNum = sheet.getLastRowNum();
//循环获取数据
for (int i = 1; i <= lastRowNum; i++) {
// 获取数据行
XSSFRow dataRow = sheet.getRow(i);
XSSFCell cellName = dataRow.getCell(1);
String name = cellName.getStringCellValue();
XSSFCell cellCity = dataRow.getCell(2);
String city = cellCity.getStringCellValue();
System.out.println(name + ":" + city);
}
// 关闭资源
in.close();
workbook.close();
}