package com.bigzhao.PoiTest;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
public class ExcelPoiTest {
public static void main(String[] args) throws Exception {
poiTest2();
}
public static void poiTest2()throws Exception{
Workbook workbook = new XSSFWorkbook("C:\\Users\\LENOVO\\Desktop\\poiTest2.xlsx");
// 获取sheet
Sheet sheet = workbook.getSheetAt(0);
// 获取sheet 中的每一行,和每一个单元格
for (int rowNum =0; rowNum <= sheet.getLastRowNum();rowNum++ ){
Row row = sheet.getRow(rowNum);
StringBuilder builder = new StringBuilder();
// 获取每一个单元格 cellNum 为什么是2 ?
for (int cellNum =0; cellNum < row.getLastCellNum();cellNum++){
// 获取索引里的每一个单元格
Cell cell = row.getCell(cellNum);
// 获取每一个单元格的内容
Object value = getCellValue(cell);
builder.append(value+" ");
}
System.out.println(builder);
}
}
public static Object getCellValue(Cell cell) {
//1.获取到单元格的属性类型
CellType cellType = cell.getCellType();
//2.根据单元格数据类型获取数据
Object value = null;
switch (cellType) {
case STRING:
value = cell.getStringCellValue();
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
break;
case NUMERIC:
if(DateUtil.isCellDateFormatted(cell)) {
//日期格式
value = cell.getDateCellValue();
}else{
//数字
value = cell.getNumericCellValue();
}
break;
case FORMULA: //公式
value = cell.getCellFormula();
break;
default:
break;
}
return value;
}
public static void poiTest1() throws Exception{
// 创建工作表
Workbook work = new XSSFWorkbook(); // 2007 版本
// 创建表单 sheet
Sheet sheet = work.createSheet();
// 创建行
Row row = sheet.createRow(2);
// 创建列
Cell cell = row.createCell(2);
// 在单元格写入
cell.setCellValue("Hello!");
// 创建样式对象
CellStyle style = work.createCellStyle();
/*style.setBorderTop(BorderStyle.DASH_DOT);
style.setBorderLeft(BorderStyle.DASH_DOT);
style.setBorderRight(BorderStyle.DASH_DOT);
style.setBorderBottom(BorderStyle.DASH_DOT);*/
// 行高和列宽
row.setHeightInPoints(50);
sheet.setColumnWidth(3,31 * 256);//设置第几列,多宽(字符宽度)所以要除以256
// 居中显示
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
// 创建字体对象
Font font = work.createFont();
font.setFontName("华文行楷");
font.setFontHeightInPoints((short)28);
style.setFont(font);
// 将之前的样式全都添加到单元格中
cell.setCellStyle(style);
// 创建文件流
FileOutputStream fo = new FileOutputStream("C:\\Users\\LENOVO\\Desktop\\poiTest1.xlsx");
// 写入文件
work.write(fo);
fo.close();
}
}