1.配置文件的準(zhǔn)備
1.導(dǎo)出功能實現(xiàn)所需要的pom文件
<!-- 導(dǎo)出到word(循環(huán)圖片) -->
<!-- word導(dǎo)出 方式:easypoi-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.4.0</version>
</dependency>
<!--注意:word中要使用循環(huán)等標(biāo)簽必須單獨導(dǎo)入以下依賴-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
這里需要注意的點?。。。。。。。。。。。。。。。。?/h4>
easypoi的版本必須在4.3.0以上,否則在導(dǎo)出圖片的時候,只會導(dǎo)出圖片的內(nèi)存地址,卻不能顯示出圖片。
2.在配置目錄下添加一個配置類
package com.state.grid.substation.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;
public class WordUtil {
public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(templatePath,"模板路徑不能為空");
Assert.notNull(temDir,"臨時文件路徑不能為空");
Assert.notNull(fileName,"導(dǎo)出文件名不能為空");
Assert.isTrue(fileName.endsWith(".docx"),"word導(dǎo)出請使用docx格式");
if (!temDir.endsWith("/")){
temDir = temDir + File.separator;
}
File dir = new File(temDir);
if (!dir.exists()) {
dir.mkdirs();
}
try {
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
}
XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
String tmpPath = temDir + fileName;
FileOutputStream fos = new FileOutputStream(tmpPath);
doc.write(fos);
// 設(shè)置強制下載不打開
response.setContentType("application/force-download");
// 設(shè)置文件名
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
OutputStream out = response.getOutputStream();
doc.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
delFileWord(temDir,fileName);//這一步看具體需求,要不要刪
}
}
/**
* 刪除零時生成的文件
*/
public static void delFileWord(String filePath, String fileName) {
File file = new File(filePath + fileName);
File file1 = new File(filePath);
file.delete();
file1.delete();
}
}
3.準(zhǔn)備一個導(dǎo)出模板(固定位置填充固定數(shù)據(jù),表格和圖片的循環(huán)導(dǎo)出)
?解釋一下模板中所填充的東西:
1.像這種:用兩個花括號括起來的變量名,到時候會將變量名所指代的數(shù)據(jù)填充進去
?2.像這種:需要將批量數(shù)據(jù)循環(huán)導(dǎo)出的表格以及圖片
?2.功能的實現(xiàn)(寫一個Controller)
調(diào)用service和mapper沒寫,具體以實際需求為準(zhǔn)
1.先理一些這個功能實現(xiàn)的邏輯:
去數(shù)據(jù)庫查表獲取想要的信息----用一個集合將這些信息都裝起來----將這些信息都插入到模板的指定位置當(dāng)中去
2.功能的實現(xiàn)(帶注釋)
這個肯定不能直接拿來運行,注意看我寫的注釋,理解代碼邏輯,我寫的很清楚,每一行代碼干了什么我都有寫。
/**
* 巡視報告的導(dǎo)出(循環(huán)圖片版)
* @param substationId
* @param calendarId
* @param request
* @param response
* @return
*/
//請求路徑是/taskResultToWord,請求方式是get請求
@RequestMapping(value = "/taskResultToWord", method = RequestMethod.GET)
//返回Result類型,傳進來變電站id,日歷id
public Result taskResultToWord(String substationId, String calendarId, HttpServletRequest request, HttpServletResponse response) throws Exception { // 分頁查詢
int code = 0;
String msg = "";
// 定義List集合list,泛型是TaskResultEquipment
List<TaskResultEquipment> list = new ArrayList<>();
// List<TaskProgress> uplist = new ArrayList<>();
//定義Map集合resmap
// Map<String, Object> resmap = new HashMap<>();
try {
//token驗證
Des3Util des = new Des3Util();
String token = request.getHeader("token");
String jsonUser = des.parseDES(token);
JSONObject jsonData = JSONObject.fromObject(jsonUser);
String userId = (String) jsonData.get("u");
String roleId = (String) jsonData.get("r");
boolean access = this.roleService.getAccess(roleId, "task/taskList");
if(access){
//定義Map集合map
Map<String, Object> map = new HashMap<>();
//將輸入的設(shè)備id添加到map集合里面
// map.put("substationId", substationId);
//將輸入的日歷id添加到calendarId里面
map.put("calendarId", calendarId);
//返回表v_task_result_equipment中的數(shù)據(jù)條數(shù)
int count = this.taskService.taskResultEquipmentCount(map);
//將查詢到的基本信息賦給taskProgress
TaskProgress taskProgress = this.taskService.taskResultInfo(map);
//添加字段startRow(開始行)的值為0
map.put("startRow", 0);
//添加字段endRow(結(jié)束行)的值為count,count的值就是表v_task_result_equipment中的數(shù)據(jù)條數(shù)
map.put("endRow", count);
//分頁查詢表v_task_result_equipment中的數(shù)據(jù),起始行是0,結(jié)束行是count,就是一頁查詢所有數(shù)據(jù),
list = this.taskService.taskResultEquipmentList(map);
System.out.println(list);
//路徑
String path1 = ResourceUtils.getURL("classpath:").getPath();
String path2 = path1.substring(1);
String terminalType = System.getProperty("os.name");
String path = "";
if (Objects.equals(terminalType, "Linux")){
path = path1.replace("ROOT/WEB-INF/classes/", "").replace("ROOT\\WEB-INF\\classes\\", "");
}else {
path = path2.replace("ROOT/WEB-INF/classes/", "").replace("ROOT\\WEB-INF\\classes\\", "");
}
System.out.println("path!!!!!!" + path);
//PATH是文件導(dǎo)出路徑resource/excel/
String PATH = path + config.getExportUrl();
//ImagePath是圖片導(dǎo)入路徑resource/cameraImage/
String ImagePath = path + config.getCameraImageUrl();
//導(dǎo)出表頭信息
//定義一個Map集合params
Map<String, Object> params = new HashMap<>();
//模板文件的路徑templatePath
String templatePath = "E:/template/patrolWord.docx"; //模板路徑
//簡單渲染文本
params.put("substationName", taskProgress.getSubstationName());
params.put("voltageLevel", taskProgress.getVoltageLevel());
params.put("viewStartTime",taskProgress.getViewStartTime());
params.put("patrolType",taskProgress.getPatrolType());
params.put("taskName",taskProgress.getTaskName());
params.put("className",taskProgress.getClassName());
params.put("totalNumber",taskProgress.getTotalNumber());
params.put("execresult1",taskProgress.getExecresult1());
params.put("execresult2",taskProgress.getExecresult2());
params.put("execresult0",taskProgress.getExecresult0());
params.put("execresult3",taskProgress.getExecresult3());
params.put("execStartTime",taskProgress.getExecStartTime());
params.put("execEndTime",taskProgress.getExecEndTime());
//聲明了一個名為alarms的變量,它是一個List類型,其中每個元素都是一個Map<String, Object>類型的鍵值對集合。
List<Map<String, Object>> alarms = new ArrayList<>();
//聲明了一個名為alarm的變量,它是一個Map類型的鍵值對集合。具體來說,這個Map對象中每個鍵都是一個String類型,每個值都是一個Object類型。
Map<String, Object> alarm;
//會遍歷list集合中的每個元素,并將每個元素賦值給循環(huán)變量taskResultEquipment。
// 在每次循環(huán)迭代中,可以使用taskResultEquipment變量來訪問集合中當(dāng)前元素的屬性和方法。
//數(shù)據(jù)來源是攝像頭
String source = "攝像頭";
//序號從1開始
int order = 1;
for (TaskResultEquipment taskResultEquipment : list){
//img_path得到表中一行數(shù)據(jù)的圖片路徑
String img_path = taskResultEquipment.getPicture();
//ImagePath是圖片導(dǎo)入路徑resource/cameraImage/,realImagePath是圖片真正的路徑
String realImagePath = ImagePath + img_path;
//將圖片路徑打印出來
System.out.println(realImagePath);
// File imagefile = new File(realImagePath);
// if (imagefile.exists()){
// taskResultEquipment.setImageData(realImagePath);
// }else {
// String errorFile = ImagePath + config.getErrorCameraImageUrl();
// taskResultEquipment.setImageData(errorFile);
// }
//創(chuàng)建了一個名為alarm的新的HashMap對象
alarm = new HashMap<>();
//將循環(huán)中獲取到的信息添加到集合里面
//變電站
// alarm.put("name", taskResultEquipment.getTaskName());
//設(shè)備名稱
alarm.put("order",order);
alarm.put("equipmentInterval", taskResultEquipment.getEquipmentInterval());
alarm.put("equipmentName", taskResultEquipment.getEquipmentName());
alarm.put("equipmentPart",taskResultEquipment.getEquipmentPart());
alarm.put("pointName", taskResultEquipment.getPointName());
alarm.put("importance", taskResultEquipment.getImportance());
alarm.put("result", taskResultEquipment.getResult());
alarm.put("realAlarmLevel", taskResultEquipment.getRealAlarmLevel());
alarm.put("confirmUser", taskResultEquipment.getConfirmUser());
alarm.put("execStartTime", taskResultEquipment.getExecStartTime());
alarm.put("source",source);
//表格內(nèi)循環(huán)添加圖片(easypoi 4.3以后才支持,不然只能打印出ImageEntity的內(nèi)存地址)
//創(chuàng)建了一個名為simage的新的ImageEntity對象,并將其賦值給simage變量。
// 具體來說,ImageEntity是一個Java類,用于表示一個圖像實體,其中包含了圖像的各種屬性和數(shù)據(jù)。
ImageEntity simage = new ImageEntity();
simage.setHeight(50);
simage.setWidth(50);
//將圖片的本地路徑導(dǎo)入進去
simage.setUrl(realImagePath);
//將simage對象的類型設(shè)置為URL類型。
//該圖像實體表示的是一個通過URL鏈接獲取的遠程圖像,而不是一個本地存儲的圖像。
simage.setType(ImageEntity.URL);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// simage.setData(out.toByteArray()); //字節(jié)流讀取
//將圖片添加進去
alarm.put("img", simage);
//alarms是一個里面元素都是map的list集合
alarms.add(alarm);
order = order + 1;
}
//Map集合params,將jobs(元素為map的list集合添加進去)
params.put("alarms", alarms);
//定義了一個表示模板文件夾路徑的字符串變量temDir,用于存儲模板文件所在的文件夾的路徑。
// 在這個例子中,temDir指向E:/template/file/word/路徑。表示文件路徑分隔符,可以是\或者/,具體取決于操作系統(tǒng)
String temDir="E:/template/" + File.separator + "file/word/"; ;//生成臨時文件存放地址
//生成文件名
Long time = new Date().getTime();
// 生成的word格式
String formatSuffix = ".docx";
// 拼接后的文件名
String fileName = time + formatSuffix;//文件名 帶后綴
//導(dǎo)出word
WordUtil.exportWord(templatePath, temDir, fileName, params, request, response);
// WordUtil.exportWord(templatePath, PATH, fileName, params, request, response);
code = 1;
}else{
msg = "token無效";
}
}catch (Exception e){
msg = "操作失敗";
}
return Result.success(code, msg,null);
}
3.導(dǎo)出的效果
1.固定信息部分:
?2.循環(huán)表格和循環(huán)圖片部分?文章來源:http://www.zghlxwxcb.cn/news/detail-434632.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-434632.html
到了這里,關(guān)于java實現(xiàn)將數(shù)據(jù)導(dǎo)出為word功能(文字,表格,圖片的循環(huán)導(dǎo)出)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!