用java要操作Excel 需要导入poi jar包 链接 https://download.csdn.net/download/qq_40258707/10451948
1.创建Excel表格
public class Test01 { @Test public void test01(){ // 创建工作簿workbook Workbook wb = new HSSFWorkbook(); // 创建工作表sheet Sheet sheet1 = wb.createSheet("秦朝美女"); // 添加行 Row row0 = sheet1.createRow(0); //添加 单元格 Cell cell00 = row0.createCell(0); //添加 单元格的值 cell00.setCellValue("漱玉"); Cell cell01 = row0.createCell(1); cell01.setCellValue("芈月"); Row row1 = sheet1.createRow(1); //设置行高 row1.setHeightInPoints((short)50); Cell cell10 = row1.createCell(0); cell10.setCellValue("漱玉"); //设置样式之 边框 CellStyle style10 = wb.createCellStyle(); style10.setBorderBottom(BorderStyle.THIN); style10.setBottomBorderColor(IndexedColors.BLUE.getIndex()); //设置样式之 垂直水平居中 style10.setAlignment(HorizontalAlignment.CENTER); style10.setVerticalAlignment(VerticalAlignment.CENTER); cell10.setCellStyle(style10); Cell cell11 = row1.createCell(1); cell11.setCellValue("芈月"); // 添加行 Row row2 = sheet1.createRow(2); //添加 单元格 Cell cell20 = row2.createCell(0); //添加 单元格的值 cell20.setCellValue("18235140708"); Cell cell21 = row2.createCell(1); CellStyle style21 = wb.createCellStyle(); cell21.setCellValue(new Date()); //设置单元格 数据 格式 CreationHelper helper = wb.getCreationHelper(); style21.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd hh:mm:ss")); cell21.setCellStyle(style21); try { //保存xls FileOutputStream fos = new FileOutputStream("d:\\108美女.xls"); wb.write(fos); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2.读取Excel
public class Test02 { @Test public void test02() throws Exception { FileInputStream fis = new FileInputStream("d:\\水浒108将.xls"); HSSFWorkbook wb = new HSSFWorkbook(fis); //文本提取 ExcelExtractor extractor = new ExcelExtractor(wb); // extractor.setIncludeSheetNames(false); System.out.println(extractor.getText()); } @Test public void test01() throws Exception { FileInputStream fis = new FileInputStream("d:\\水浒108将.xls"); Workbook wb = new HSSFWorkbook(fis); Sheet sheet0 = wb.getSheetAt(0); for (int i = 0; i <= sheet0.getLastRowNum(); i++) { Row row = sheet0.getRow(i); if(row == null){ continue; } for (int j = 0; j <= row.getLastCellNum(); j++) { Cell cell = row.getCell(j); if(cell == null){ continue; } System.out.println(cell.getStringCellValue()); } System.out.println(); } } }