服务器端文档组件
- 项目中需要使用文档组件操作文档(导入,导出)
- 操作文档的框架有如下几种
1.概述
- 1.Apache POI是用Java编写的免费开源的跨平台的 Java API
- 2.Apache POI提供API给Java程序对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式文档读和写的功能
- 3.POI为
Poor Obfuscation Implementation
的首字母缩写,意为:可怜的模糊实现
2.功能
3.依赖
4.特点
5.不同文档操作步骤
1.操作Excel
1.Excel中的表单、工作表、行、单元格的关系
2.常用的类和方法
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
hssfWorkbook = new HSSFWorkbook(InputStream inputStream);
hssfWorkbook.close();
HSSFSheet hssfSheet = hssfWorkbook.createSheet();
HSSFSheet sheetname= hssfWorkbook.createSheet(String sheetname);
hssfWorkbook.setActiveSheet(int index);
HSSFSheet getSheet(String sheetName);
getSheetAt(int index);
int getNumberOfSheets();
HSSFRow hssfRow = hssfSheet.createRow(int rownum);
hssfRow.setHeight(height);
hssfRow.setHeightInPoints(height);
hssfRow.setRowNum(int rowIndex);
hssfRow.setZeroHeight(false);
hssfRow.setRowStyle(cellStyle);
getLastRowNum();
hssfSheet.autoSizeColumn(int column);
hssfSheet.setColumnWidth(int columnIndex, int width);
HSSFCell hssfCell = hssfRow.createCell(int column);
HSSFCell hssfCell = hssfRow.createCell(int column,CellType type);
hssfCell.setCellStyle(HSSFCellStyle style);
hssfCell.setCellValue(Date value);
hssfCell.setAsActiveCell();
hssfCell.setBlank();
hssfCell.setCellFormula(String formula);
hssfCell.setCellType(CellType cellType);
HSSFCell getCell(shot index);
HSSFCell getCell(CellReference.convertColStringToIndex(“A”)); 根据列名英文字母获取。
short getLastCellNum();
String getStringCellValue();
HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
cellStyle.setFillBackgroundColor(short bg);
cellStyle.setFillForegroundColor(short bg);
cellStyle.setFillPattern(FillPatternType fp);
cellStyle.setFont(HSSFFont hf);
cellStyle.setAlignment(HorizontalAlignment align);
cellStyle.setVerticalAlignment(VerticalAlignment align);
cellStyle.setVerticalAlignment(VerticalAlignment align);
cellStyle.setBorderTop(BorderStyle border);
cellStyle.setBorderBottom(BorderStyle border);
cellStyle.setBorderLeft(BorderStyle border);
cellStyle.setBorderRight(BorderStyle border);
cellStyle.setTopBorderColor(IndexedColors.RED.getIndex());
cellStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex());
cellStyle.setLeftBorderColor(IndexedColors.PINK.getIndex());
cellStyle.setRightBorderColor(IndexedColors.CORAL.getIndex());
cellStyle.setHidden(false);
indention = 2; cellStyle.setIndention(indention);
cellStyle.setLocked(true);
cellStyle.setRotation(rotation);
cellStyle.setShrinkToFit(false);
cellStyle.setQuotePrefixed(false);
cellStyle.setReadingOrder(order);
cellStyle.setUserStyleName("测试");
cellStyle.setWrapText(true);
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
short format = hssfDataFormat.getFormat("@");
cellStyle.setDataFormat(format);
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
short format = hssfDataFormat.getFormat("yyyy年m月d日");
cellStyle.setDataFormat(format);
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
short format = HSSFDataFormat.getBuiltinFormat("0.00");
BuiltinFormats cellStyle.setDataFormat(format);
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
short format = hssfDataFormat.getFormat("¥#,##0");
cellStyle.setDataFormat(format);
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
short format = hssfDataFormat.getFormat("[DbNum2][$-804]0");
cellStyle.setDataFormat(format);
hssfSheet.addMergedRegion(CellRangeAddress region);
new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol);
CellRangeAddress创建新的单元格范围。索引从零开始(开始行,结束行,开始列,结束列)
hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
hssfSheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
write();
write(File newFile);
write(OutputStream stream);
HSSFCellStyle cellFontStyle = hssfWorkbook.createCellStyle();
HSSFFont hssfFont = hssfWorkbook.createFont();
hssfFont.setColor(IndexedColors.BLUE.getIndex());
hssfFont.setBold(true);
hssfFont.setCharSet();
hssfFont.setFontHeight();
hssfFont.setFontHeightInPoints();
hssfFont.setFontName("楷体");
hssfFont.setItalic(true);
hssfFont.setStrikeout(true);
hssfFont.setTypeOffset(Font.SS_SUPER);
hssfFont.setUnderline(Font.U_SINGLE_ACCOUNTING);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
2.从Excel读取数据
- 1.读取普通数据
@Test
public void TestExcelRead() throws IOException {
String filePath = "E:\\Apache POI\\template.xls";
FileInputStream fileInputStream = new FileInputStream(filePath);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileInputStream);
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
int lastRowNum = hssfSheet.getLastRowNum();
short lastCellNum = hssfSheet.getRow(0).getLastCellNum();
Iterator<Row> iterator = hssfSheet.iterator();
while (iterator.hasNext()) {
HSSFRow row = (HSSFRow) iterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
HSSFCell cell = (HSSFCell) cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue());
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
}
System.out.print(" -- ");
}
System.out.println();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 2.读取带有公式计算的数据
@Test
public void read2() throws IOException {
FileInputStream fileInputStream = new FileInputStream(".\\datafiles\\readformula.xls");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
short cols = sheet.getRow(0).getLastCellNum();
for (int r = 0; r < rows; r++) {
HSSFRow row = sheet.getRow(r);
for (int c = 0; c < cols; c++) {
HSSFCell cell = row.getCell(c);
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue());
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case FORMULA:
System.out.println(cell.getNumericCellValue());
break;
}
System.out.print(" -- ");
}
System.out.println();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 3.读取带有密码的Excel
@Test
public void read2() throws IOException {
FileInputStream fileInputStream = new FileInputStream(".\\datafiles\\employee.xls");
String password = "123456";
HSSFWorkbook hssfWorkbook = (HSSFWorkbook) HSSFWorkbookFactory.create(fileInputStream, password);
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
short cols = sheet.getRow(0).getLastCellNum();
for (int r = 0; r < rows; r++) {
HSSFRow row = sheet.getRow(r);
for (int c = 0; c < cols; c++) {
HSSFCell cell = row.getCell(c);
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue());
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case FORMULA:
System.out.println(cell.getNumericCellValue());
break;
}
System.out.print(" -- ");
}
System.out.println();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 4.将Excel数据读取到Map中
@Test
public void read3() throws IOException {
FileInputStream fileInputStream = new FileInputStream(".\\datafiles\\student.xls");
HSSFWorkbook hssfWorkbook = (HSSFWorkbook) HSSFWorkbookFactory.create(fileInputStream);
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
int rows = sheet.getLastRowNum();
HashMap<String, String> data = new HashMap<>();
for (int r = 0; r < rows; r++) {
String key = sheet.getRow(r).getCell(0).getStringCellValue();
String value = sheet.getRow(r).getCell(1).getStringCellValue();
data.put(key,value);
}
for (Map.Entry<String, String> entry : data.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
3.向Excel写入数据
- 1.写入数据接口案例
@Test
public void TestExcelWrite(){
String fileName = "TestExcelWrite";
String filePath = "E:\\Apache POI\\"+ fileName +".xls";
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFCellStyle cellBGStyle = hssfWorkbook.createCellStyle();
cellBGStyle.setAlignment(HorizontalAlignment.CENTER);
cellBGStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
cellBGStyle.setBorderTop(BorderStyle.HAIR);
cellBGStyle.setBorderBottom(BorderStyle.DOTTED);
cellBGStyle.setBorderLeft(BorderStyle.DOUBLE);
cellBGStyle.setBorderRight(BorderStyle.DASH_DOT);
cellBGStyle.setTopBorderColor(IndexedColors.RED.getIndex());
cellBGStyle.setBottomBorderColor(IndexedColors.BLUE.getIndex());
cellBGStyle.setLeftBorderColor(IndexedColors.PINK.getIndex());
cellBGStyle.setRightBorderColor(IndexedColors.CORAL.getIndex());
HSSFDataFormat hssfDataFormat = hssfWorkbook.createDataFormat();
hssfDataFormat.getFormat("@");
short format = hssfDataFormat.getFormat("yyyy年m月d日");
short format = HSSFDataFormat.getBuiltinFormat("0.00");
short format = HSSFDataFormat.getBuiltinFormat("0.00E+00");
cellBGStyle.setDataFormat(format);
short indention = 2;
cellBGStyle.setIndention(indention);
short rotation = 80;
cellBGStyle.setQuotePrefixed(false);
short order = 2;
cellBGStyle.setReadingOrder(order);
cellBGStyle.setUserStyleName("测试");
cellBGStyle.setWrapText(true);
cellBGStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellBGStyle.setFillPattern(FillPatternType.FINE_DOTS);
HSSFCellStyle cellFontStyle = hssfWorkbook.createCellStyle();
HSSFFont hssfFont = hssfWorkbook.createFont();
hssfFont.setColor(IndexedColors.BLUE.getIndex());
hssfFont.setBold(true);
hssfFont.setFontName("楷体");
hssfFont.setItalic(true);
hssfFont.setUnderline(Font.U_SINGLE_ACCOUNTING);
cellFontStyle.setFont(hssfFont);
HSSFSheet hssfSheet = hssfWorkbook.createSheet();
HSSFSheet test = hssfWorkbook.createSheet("test");
HSSFHeader header = hssfSheet.getHeader();
header.setCenter("人员权限信息");
hssfSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
hssfSheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0));
hssfWorkbook.setActiveSheet(1);
int colNum = 0;
for (int i=0; i<9; i++) {
HSSFRow hssfRow = hssfSheet.createRow(i);
short height = 2000;
hssfRow.setHeight(height);
for(int j=0; j<=i; j++){
HSSFCell hssfCell = hssfRow.createCell(j);
if(i%2==0){
hssfCell.setCellStyle(cellBGStyle);
hssfCell.setAsActiveCell();
}else {
hssfCell.setCellStyle(cellFontStyle);
}
hssfCell.setCellValue(new Date());
colNum = j;
}
}
for(int col=0; col<=colNum; col++){
hssfSheet.autoSizeColumn(col);
}
try {
hssfWorkbook.write(new FileOutputStream(filePath));
} catch (IOException e) {
log.error("路径错误{} {}",filePath,new Date());
e.printStackTrace();
}
try {
hssfWorkbook.close();
} catch (IOException e) {
log.error("Excel表单关闭错误{}", new Date());
e.printStackTrace();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 2.写入数据标准模板
@Test
public void write3() throws IOException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet("Emp Info");
HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
Object empData[][] = {
{"EmpID","Name","Job"},
{101,"David","Java"},
{102,"Smith","Manager"},
{103,"Son","Analyst"}
};
int rowCount = 0;
for (Object emp[]:empData) {
HSSFRow row = hssfSheet.createRow(rowCount++);
int colCount = 0;
for (Object value : emp) {
HSSFCell cell = row.createCell(colCount++);
if(value instanceof String)
cell.setCellValue((String)value);
if(value instanceof Integer)
cell.setCellValue((Integer)value);
if(value instanceof Boolean)
cell.setCellValue((Boolean)value);
}
}
String filePath = ".\\datafiles\\employee.xls";
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
hssfWorkbook.write(fileOutputStream);
System.out.println("Employee.xls file written successfully");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 3.向桌面写入数据
@Test
public void write1() throws IOException {
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
File file = new File(filePath);
OutputStream outputStream = new FileOutputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("订单号");
row.createCell(2).setCellValue("下单时间");
row.createCell(3).setCellValue("个数");
row.createCell(4).setCellValue("单价");
row.createCell(5).setCellValue("订单金额");
row.setHeightInPoints(30);
HSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("NO00001");
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
sheet.setColumnWidth(2, 20 * 256);
HSSFCell cell2 = row1.createCell(2);
cell2.setCellStyle(cellStyle2);
cell2.setCellValue(new Date());
row1.createCell(3).setCellValue(2);
HSSFCellStyle cellStyle3 = workbook.createCellStyle();
cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
HSSFCell cell4 = row1.createCell(4);
cell4.setCellStyle(cellStyle3);
cell4.setCellValue(29.5);
HSSFCellStyle cellStyle4 = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("华文行楷");
font.setFontHeightInPoints((short)15);
font.setColor(IndexedColors.RED.getIndex());
cellStyle4.setFont(font);
HSSFCell cell5 = row1.createCell(5);
cell5.setCellFormula("D2*E2");
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
cell5 = e.evaluateInCell(cell5);
System.out.println(cell5.getNumericCellValue());
workbook.setActiveSheet(0);
workbook.write(outputStream);
outputStream.close();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 4.写入带有公式的表格
@Test
public void write3() throws IOException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet("Numbers");
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue(10);
row.createCell(1).setCellValue(20);
row.createCell(2).setCellValue(30);
row.createCell(3).setCellFormula("A1*B1*C1");
FileOutputStream fileOutputStream = new FileOutputStream(".\\datafiles\\calc.xlsx");
hssfWorkbook.write(fileOutputStream);
fileOutputStream.close();
hssfWorkbook.close();
System.out.println("calc.xlsx created with formula cell...");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 5.将Map中的数据写入表格
@Test
public void write4() throws IOException {
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet("Student data");
Map<String, String> data = new HashMap<>();
data.put("101","李四");
data.put("102","张三");
data.put("103","赵六");
data.put("104","王五");
int rowCount = 0;
for (Map.Entry<String, String> entry : data.entrySet()) {
HSSFRow row = sheet.createRow(rowCount++);
row.createCell(0).setCellValue((String)entry.getKey());
row.createCell(1).setCellValue((String)entry.getValue());
}
FileOutputStream fileOutputStream = new FileOutputStream(".\\datafiles\\student.xlsx");
hssfWorkbook.write(fileOutputStream);
hssfWorkbook.close();
fileOutputStream.close();
System.out.println("student.xlsx created...");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 6.将数据库中的数据写入表单中
@Test
public void write5() throws SQLException, IOException {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis_plus","root","root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from t_user");
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet("User Data");
HSSFCellStyle cellStyle = hssfWorkbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
String[] str = new String[]{"id","name","age","email"};
HSSFRow row1 = sheet.createRow(0);
for (int c = 0; c < str.length; c++) {
HSSFCell cell = row1.createCell(c);
cell.setCellValue(str[c]);
cell.setCellStyle(cellStyle);
}
int rowCount = 1;
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String email = resultSet.getString("email");
HSSFRow row = sheet.createRow(rowCount++);
HSSFCell cell = row.createCell(0);
HSSFCell cell1 = row.createCell(1);
HSSFCell cell2 = row.createCell(2);
HSSFCell cell3 = row.createCell(3);
cell.setCellValue(id);
cell.setCellStyle(cellStyle);
cell1.setCellValue(name);
cell1.setCellStyle(cellStyle);
cell2.setCellValue(age);
cell2.setCellStyle(cellStyle);
cell3.setCellValue(email);
cell3.setCellStyle(cellStyle);
}
sheet.autoSizeColumn(3);
FileOutputStream fileOutputStream = new FileOutputStream(".\\datafiles\\User.xls");
hssfWorkbook.write(fileOutputStream);
hssfWorkbook.close();
fileOutputStream.close();
connection.close();
System.out.println("Success");
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
2.操作Word
1.Word文档中范围,小节,段落,文本的关系(HWPFDocument)
2.常用类和方法
HWPFDocument doc = newHWPFDocument(InputStream istream)
Range range = doc.getRange();
Range overallRange = hwpfDocument.getOverallRange();
Range headerStoryRange = hwpfDocument.getHeaderStoryRange();
Range footnoteRange = hwpfDocument.getFootnoteRange();
Range mainTextboxRange = hwpfDocument.getMainTextboxRange();
Range commentsRange = hwpfDocument.getCommentsRange();
Range endnoteRange = hwpfDocument.getEndnoteRange();
String text = range.text();
Section section = range.getSection(int index);
int sectionsNum = range.numSections();
String text = Section.text();
Paragraph paragraph = section.getParagraph(int index);
int paragraphsNum = section.numParagraphs();
String text = paragraph.text();
CharacterRun characterRun = paragraph.getCharacterRun(int index);
int characterRuns = paragraph.numCharacterRuns();
String text = characterRun.text();
characterRun.setBold(true);
characterRun.setFontSize(100);
characterRun.setItalic(true);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
1.Word文档中的段落,文本,表格关系(XWPFDocument)
2.常用类和方法
XWPFDocument doc = new XWPFDocument();
XWPFChart chart = doc.createChart();
XWPFEndnote endnote = doc.createEndnote();
XWPFFooter footer = doc.createFooter(HeaderFooterType type);
XWPFFootnote footnote = doc.createFootnote();
XWPFHeader header = doc.createHeader(HeaderFooterType type);
XWPFHeaderFooterPolicy headerFooterPolicy = doc.createHeaderFooterPolicy();
XWPFNumbering numbering = doc.createNumbering();
XWPFParagraph paragraph = doc.createParagraph();
XWPFStyles styles = doc.createStyles();
XWPFParagraph paragraph = doc.createParagraph();
XWPFRun run = paragraph.createRun();
XWPFTable table = doc.createTable();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
1.从Word读取数据
- 1.从Word文档中读取指定节点指定段落的内容
@Test
public void wordWrite3() throws IOException {
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/readContext.doc";
FileInputStream fis = new FileInputStream(filePath);
HWPFDocument doc = new HWPFDocument(fis);
Range range = doc.getRange();
int sectionsNum = range.numSections();
System.out.println("sectionsNum:" + sectionsNum);
for (int i = 0; i < sectionsNum; i++) {
Section section = range.getSection(i);
int paragraphsNum = section.numParagraphs();
System.out.println("paragraphsNum:" + paragraphsNum);
for (int j = 0; j < paragraphsNum; j++) {
Paragraph paragraph = section.getParagraph(j);
String text = paragraph.text();
System.out.println("小节:" + (i+1) + ",段落:" + (j+1) + ",内容:" + text);
}
}
FileOutputStream out = new FileOutputStream(".\\datafiles\\test.doc");
out.flush();
doc.write(out);
fis.close();
out.close();
doc.close();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 2.从Word文档中读取图片并写入到指定位置
@Slf4j
public class PoiUtil {
public static String getFilePrefix(File file){
String wholeFileName = file.getName();
int lastPointIndex = wholeFileName.lastIndexOf(".");
return wholeFileName.substring(0, lastPointIndex);
}
public static String getFileSuffix(File file){
String fileName = file.getName();
return getFileType(fileName);
}
public static String getFileType(String fileName) {
String[] strArray = fileName.split("\\.");
int suffixIndex = strArray.length -1;
return strArray[suffixIndex];
}
public synchronized static void fetchPictureFromWord(File wordFile, String targetPath) {
String absolutePath = wordFile.getAbsolutePath();
String fileType = POIUtil.getFileType(absolutePath);
String fileName = getFilePrefix(wordFile);
int numberId=1;
switch (fileType.toLowerCase()){
case "doc":
try(HWPFDocument hwpfDocument = new HWPFDocument(new FileInputStream(absolutePath))){
PicturesTable picturesTable = hwpfDocument.getPicturesTable();
List<Picture> pictures = picturesTable.getAllPictures();
for (Picture picture : pictures) {
String pictureFiePath = targetPath + File.separator + fileName + numberId +"."+ picture.suggestFileExtension();
log.info("doc pictureFiePath:" + pictureFiePath);
try(OutputStream out = new FileOutputStream(pictureFiePath)){
picture.writeImageContent(out);
}
numberId++;
}
}catch (IOException e) {
log.error("错误的文件:{}",e);
log.error("出错文件路径",absolutePath);
}
break;
case "docx":
try(XWPFDocument xwpfDocument=new XWPFDocument(new FileInputStream(absolutePath))){
List<XWPFPictureData> xwpfPictureDataList = xwpfDocument.getAllPictures();
if(null!=xwpfPictureDataList && xwpfPictureDataList.size()>0){
for (XWPFPictureData item:xwpfPictureDataList) {
byte[] bytes = item.getData();
String pictureFiePath = targetPath + File.separator + fileName + numberId + "." + item.suggestFileExtension();
log.info("docx pictureFiePath:" + pictureFiePath);
File file=new File(pictureFiePath);
if(file.exists()){
file.delete();
}
try(FileOutputStream fos = new FileOutputStream(pictureFiePath)){
fos.write(bytes);
}
numberId++;
}
}
} catch (IOException e) {
log.error("错误的文件:{}",e);
log.error("出错文件路径",absolutePath);
}
break;
default:
log.error("{}无效的文件格式:{}",wordFile,fileType);
break;
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
@Test
public void test(){
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.doc";
File wordFile = new File(filePath);
String targetPath = wordFile.getParentFile().getPath();
POIUtil.fetchPictureFromWord(wordFile,targetPath);
}
2.向Word写入数据
- (XWPF支持读写功能,HWPF对于写功能只实现一部分)
- 1.向Word文档写入List数据
public static void writeDataToWord(String fileName, List<String> data) throws IOException {
try(FileOutputStream out = new FileOutputStream(fileName)){
XWPFDocument xwpfDocument=new XWPFDocument();
XWPFParagraph xwpfParagraph;
XWPFRun run;
for (String lineData:data) {
xwpfParagraph= xwpfDocument.createParagraph();
run = xwpfParagraph.createRun();
run.setText(lineData);
}
xwpfDocument.write(out);
xwpfDocument.close();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
@Test
public void test() throws IOException {
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.doc";
ArrayList<String> data = new ArrayList<>();
data.add("你是猪");
data.add("you are pig");
data.add("我是帅哥");
data.add("I am coolMan");
POIUtil.writeDataToWord(filePath,data);
}
- 2.向Word文档中写入简单表格
@Test
public void wordWrite4() throws IOException {
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/write.doc";
XWPFDocument doc = new XWPFDocument();
XWPFTable table = doc.createTable();
for (int i = 0; i < 9; i++) {
XWPFTableRow row = table.createRow();
for (int j = 0; j <= i; j++) {
XWPFTableCell cell = row.createCell();
cell.setText((j+1) + "*" + (i+1) + "=" + (j+1)*(i+1));
cell.setWidth("1024");
}
}
FileOutputStream out = new FileOutputStream(filePath);
out.flush();
doc.write(out);
out.close();
doc.close();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
6.Java Web文档操作
1.导入
1.依赖
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>4.0.0version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.0.0version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>1.4version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.1version>
dependency>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
Caused by: org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.web.multipart.commons.CommonsMultipartResolver]:
Factory method 'getCommonsMultipartResolver' threw exception; nested
exception is java.lang.NoClassDefFoundError:
org/apache/commons/fileupload/disk/DiskFileItemFactory
2.配置类
package com.wd.config;
import org.springframework.context.annotation.Bean; import
org.springframework.context.annotation.Configuration; import
org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Configuration public class ImportConfig {
@Bean
public CommonsMultipartResolver getCommonsMultipartResolver(){
return new CommonsMultipartResolver();
} }
3.导入接口
@SuppressWarnings("resource")
@RequestMapping("/import")
public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
System.out.println(file);
InputStream inputStream = file.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheetAt(0);
System.out.println(sheet);
int lastRowNum = sheet.getLastRowNum();
System.out.println(lastRowNum);
for (int i = 2; i <= lastRowNum; i++) {
HSSFRow row = sheet.getRow(i);
int id = (int) row.getCell(0).getNumericCellValue();
String name = row.getCell(1).getStringCellValue();
int age = (int) row.getCell(2).getNumericCellValue();
System.out.println(id + "-" + name + "-" + age);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
2.导出
1.依赖
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poiartifactId>
<version>4.0.0version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.0.0version>
dependency>
2.接口
@SuppressWarnings("resource")
@RequestMapping("/export")
public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception {
String[] tableHeaders = {"id", "姓名", "年龄"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Font font = workbook.createFont();
font.setColor(IndexedColors.RED.getIndex());
font.setBold(true);
cellStyle.setFont(font);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
HSSFRow row = sheet.createRow(0);
HSSFCell beginCell = row.createCell(0);
beginCell.setCellValue("通讯录");
beginCell.setCellStyle(cellStyle);
row = sheet.createRow(1);
for (int i = 0; i < tableHeaders.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(tableHeaders[i]);
cell.setCellStyle(cellStyle);
}
List<User> users = new ArrayList<>();
users.add(new User(1, "张三", 20));
users.add(new User(2, "李四", 21));
users.add(new User(3, "王五", 22));
for (int i = 0; i < users.size(); i++) {
row = sheet.createRow(i + 2);
User user = users.get(i);
row.createCell(0).setCellValue(user.getId());
row.createCell(1).setCellValue(user.getName());
row.createCell(2).setCellValue(user.getAge());
}
OutputStream outputStream = response.getOutputStream();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=template.xls");
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
3.前端JSP
<%--
Created by IntelliJ IDEA.
User: 32929
Date: 2022/11/26
Time: 13:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试</title>
</head>
<body>
<a href="http://localhost:8989/springboot_test/export">导出</a> <br/>
<form action="http://localhost:8989/springboot_test/import" enctype="multipart/form-data" method="post">
<input type="file" name="file"/><br/>
<input type="submit" value="导入Excel"/>
</form>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
2.JXL
- Java Excel是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件。jxl 由于其小巧 易用的特点, 逐渐已经取代了 POI-excel的地位, 成为了越来越多的java开发人员生成excel文件的首选。
3.excelPOI
4.easyExcel
5.GrapeCity Documents