提交 1c5186b7 作者: obcy

Merge remote-tracking branch 'origin/master'

...@@ -184,19 +184,35 @@ ...@@ -184,19 +184,35 @@
<artifactId>spring-boot-starter-thymeleaf</artifactId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> </dependency>
<!--word-html处理工具--> <!--word-html处理工具-->
<!-- <dependency>-->
<!-- <groupId>com.aspose</groupId>-->
<!-- <artifactId>aspose-words</artifactId>-->
<!-- <version>15.12.0</version>-->
<!-- <scope>system</scope>-->
<!-- <systemPath>${basedir}/lib/aspose-words-15.12.0-jdk16.jar</systemPath>-->
<!-- </dependency>-->
<dependency> <dependency>
<groupId>com.aspose</groupId> <groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId> <artifactId>aspose-words</artifactId>
<version>15.12.0</version> <version>18.6</version>
<scope>system</scope> <scope>system</scope>
<systemPath>${basedir}/lib/aspose-words-15.12.0-jdk16.jar</systemPath> <systemPath>${basedir}/lib/aspose-words-18.6-jdk16-crack.jar</systemPath>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.fusesource.hawtbuf</groupId> <groupId>org.fusesource.hawtbuf</groupId>
<artifactId>hawtbuf</artifactId> <artifactId>hawtbuf</artifactId>
<version>1.11</version> <version>1.11</version>
</dependency> </dependency>
<!-- excel工具包 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -59,6 +59,19 @@ public class KbFileController { ...@@ -59,6 +59,19 @@ public class KbFileController {
} }
/** /**
* 预览文档接口
* @param fileName
* @param filePath
* @param userName
* @param model
* @return
*/
@GetMapping("/viewer")
public String viewerDocFile(String fileName, String filePath, String userName, Model model) {
return localFileService.viewerDocFile(fileName,filePath,userName,model);
}
/**
* 编辑文档时的回调接口 * 编辑文档时的回调接口
* @param request * @param request
* @param response * @param response
......
...@@ -6,11 +6,10 @@ import com.baomidou.mybatisplus.core.metadata.IPage; ...@@ -6,11 +6,10 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zzsn.knowbase.entity.KbAuthorizedUser; import com.zzsn.knowbase.entity.KbAuthorizedUser;
import com.zzsn.knowbase.entity.KnowFile; import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge; import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.entity.KnowledgeExcel;
import com.zzsn.knowbase.service.IKnowledgeService; import com.zzsn.knowbase.service.IKnowledgeService;
import com.zzsn.knowbase.service.ILocalFileService; import com.zzsn.knowbase.service.ILocalFileService;
import com.zzsn.knowbase.util.DocUtil; import com.zzsn.knowbase.util.*;
import com.zzsn.knowbase.util.HttpUtil;
import com.zzsn.knowbase.util.SpringContextUtils;
import com.zzsn.knowbase.vo.IntelligentQaParam; import com.zzsn.knowbase.vo.IntelligentQaParam;
import com.zzsn.knowbase.vo.KnowledgeParam; import com.zzsn.knowbase.vo.KnowledgeParam;
import com.zzsn.knowbase.vo.KnowledgeVO; import com.zzsn.knowbase.vo.KnowledgeVO;
...@@ -26,7 +25,11 @@ import org.springframework.web.multipart.MultipartHttpServletRequest; ...@@ -26,7 +25,11 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils; import org.springframework.web.util.WebUtils;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
...@@ -101,6 +104,7 @@ public class KnowledgeController { ...@@ -101,6 +104,7 @@ public class KnowledgeController {
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
List<Result<KnowFile>> resultList = localFileService.upload(fileMap); List<Result<KnowFile>> resultList = localFileService.upload(fileMap);
KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo(); KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
knowledge.setImportData(0);
CompletableFuture.runAsync(()-> this.add(resultList,knowledge,userInfo)); CompletableFuture.runAsync(()-> this.add(resultList,knowledge,userInfo));
return Result.OK("添加成功!"); return Result.OK("添加成功!");
} }
...@@ -137,7 +141,7 @@ public class KnowledgeController { ...@@ -137,7 +141,7 @@ public class KnowledgeController {
*/ */
@DeleteMapping(value = "/delete") @DeleteMapping(value = "/delete")
public Result<?> delete(@RequestParam(name = "ids") String ids) { public Result<?> delete(@RequestParam(name = "ids") String ids) {
CompletableFuture.runAsync(()-> knowledgeService.deleteKnowledge(ids)); knowledgeService.deleteKnowledge(ids);
return Result.OK("删除成功!"); return Result.OK("删除成功!");
} }
...@@ -168,4 +172,33 @@ public class KnowledgeController { ...@@ -168,4 +172,33 @@ public class KnowledgeController {
} }
return Result.error("响应失败"); return Result.error("响应失败");
} }
/**
* 通过excel导入
*
* @return
*/
@RequestMapping(value = "/importInfo", method = RequestMethod.POST)
public Result<?> importInfo(HttpServletRequest request, HttpServletResponse response) {
KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
assert userInfo != null;
knowledgeService.doImportInfo(request,userInfo.getId());
return Result.OK("导入正在后台进行");
}
/**
* 下载导入模板
*/
@RequestMapping(value = "/download")
public Result<?> download(HttpServletRequest request, HttpServletResponse response) {
try {
File fileDir = ExcelExportUtil.getFileDir();
List<KnowledgeExcel> dataList = new ArrayList<>();
String filePath = fileDir.getAbsolutePath() + File.separator + "info.xlsx";
ExcelExportUtil.writeExcelFront(dataList, "知识库列表导入模板", filePath, KnowledgeExcel.class);
ExcelExportUtil.download(response, filePath, true);
} catch (Exception e) {
e.printStackTrace();
}
return Result.OK();
}
} }
...@@ -102,6 +102,7 @@ public class Knowledge implements Serializable { ...@@ -102,6 +102,7 @@ public class Knowledge implements Serializable {
* 知识库id * 知识库id
*/ */
private String kbKnowledgeId; private String kbKnowledgeId;
private String content;
/** /**
* 类型 * 类型
*/ */
...@@ -111,6 +112,7 @@ public class Knowledge implements Serializable { ...@@ -111,6 +112,7 @@ public class Knowledge implements Serializable {
private List<Content> contents; private List<Content> contents;
private List<KnowFile> files; private List<KnowFile> files;
private Integer score; private Integer score;
private Integer importData;
} }
......
package com.zzsn.knowbase.entity;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.jeecgframework.poi.excel.annotation.Excel;
import java.io.Serializable;
import java.util.List;
/**
* @Description: 知识
* @Author: chenshiqiang
* @Version: V1.0
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class KnowledgeExcel {
/**
* 标题
*/
@ExcelProperty(value = "标题", index = 0)
private String title;
@ExcelProperty(value = "正文", index = 1)
private String content;
/**
* 作者
*/
@ExcelProperty(value = "作者", index = 2)
private String author;
/**
* 来源
*/
@ExcelProperty(value = "来源", index = 3)
private String origin;
/**
* 发布时间
*/
@ExcelProperty(value = "发布时间", index = 4)
private String publishDate;
}
...@@ -3,6 +3,8 @@ package com.zzsn.knowbase.kafka.cloudstream; ...@@ -3,6 +3,8 @@ package com.zzsn.knowbase.kafka.cloudstream;
import org.springframework.cloud.stream.annotation.Output; import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageChannel;
import java.net.DatagramSocket;
/** /**
* @author chenshiqiang * @author chenshiqiang
* @Description 知识信息通道 * @Description 知识信息通道
...@@ -18,5 +20,6 @@ public interface KnowledgeChannel { ...@@ -18,5 +20,6 @@ public interface KnowledgeChannel {
@Output @Output
MessageChannel knowledgeContents(); MessageChannel knowledgeContents();
@Output
MessageChannel knowledgeExcelContents();
} }
...@@ -35,6 +35,7 @@ public class KnowledgeMessage { ...@@ -35,6 +35,7 @@ public class KnowledgeMessage {
* 审核状态 * 审核状态
*/ */
private Integer verifyStatus; private Integer verifyStatus;
private Integer verifyTime;
/** /**
* 审核人名字 * 审核人名字
*/ */
...@@ -48,6 +49,7 @@ public class KnowledgeMessage { ...@@ -48,6 +49,7 @@ public class KnowledgeMessage {
* 类型 * 类型
*/ */
private String type; private String type;
private String author;
private List<Content> contents; private List<Content> contents;
......
...@@ -32,4 +32,10 @@ public class ProduceInfo { ...@@ -32,4 +32,10 @@ public class ProduceInfo {
Message<String> message = MessageBuilder.withPayload(msg).build(); Message<String> message = MessageBuilder.withPayload(msg).build();
channel.knowledgeContents().send(message); channel.knowledgeContents().send(message);
} }
public void sendKnowledgeExcelContents(KnowledgeMessage knowledgeMessage) {
String msg = JSON.toJSONString(knowledgeMessage);
Message<String> message = MessageBuilder.withPayload(msg).build();
channel.knowledgeExcelContents().send(message);
}
} }
...@@ -6,6 +6,9 @@ import com.zzsn.knowbase.entity.KnowFile; ...@@ -6,6 +6,9 @@ import com.zzsn.knowbase.entity.KnowFile;
import com.zzsn.knowbase.entity.Knowledge; import com.zzsn.knowbase.entity.Knowledge;
import com.zzsn.knowbase.vo.KnowledgeParam; import com.zzsn.knowbase.vo.KnowledgeParam;
import com.zzsn.knowbase.vo.KnowledgeVO; import com.zzsn.knowbase.vo.KnowledgeVO;
import com.zzsn.knowbase.vo.Result;
import javax.servlet.http.HttpServletRequest;
/** /**
* @Description: 知识服务 * @Description: 知识服务
...@@ -45,4 +48,8 @@ public interface IKnowledgeService { ...@@ -45,4 +48,8 @@ public interface IKnowledgeService {
IPage<KnowledgeVO> listFromPython(KnowledgeParam knowledgeParam, Integer pageNo, Integer pageSize, String column, String order); IPage<KnowledgeVO> listFromPython(KnowledgeParam knowledgeParam, Integer pageNo, Integer pageSize, String column, String order);
KnowledgeVO getById(String id); KnowledgeVO getById(String id);
Result<?> doImportInfo(HttpServletRequest request,String userId);
void doExcel(HttpServletRequest request, String fileSuffix,String userId);
} }
...@@ -56,6 +56,16 @@ public interface ILocalFileService { ...@@ -56,6 +56,16 @@ public interface ILocalFileService {
String editDocFile(String fileName, String filePath, String userName, Model model); String editDocFile(String fileName, String filePath, String userName, Model model);
/** /**
* 预览文档
* @param fileName
* @param filePath
* @param userName
* @param model
* @return
*/
String viewerDocFile(String fileName, String filePath, String userName, Model model);
/**
* 编辑文档时的回调接口 * 编辑文档时的回调接口
* @param request * @param request
* @param response * @param response
......
package com.zzsn.knowbase.service.impl;
import com.zzsn.knowbase.service.IKnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
/**
* Description: 异步处理service
* Author: EDY
* Date: 2023/7/26
*/
@Service
public class AsyncService {
@Autowired
@Lazy
IKnowledgeService knowledgeService;
//异步执行文件解析
@Async
public void doimport(HttpServletRequest request, String fileSuffix,String userId) {
knowledgeService.doExcel(request, fileSuffix,userId);
}
}
...@@ -164,12 +164,23 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -164,12 +164,23 @@ public class LocalFileServiceImpl implements ILocalFileService {
model.addAttribute("document", document); model.addAttribute("document", document);
// 如果该格式不支持编辑,则返回预览页面 // 如果该格式不支持编辑,则返回预览页面
if (!documentService.canEdit(document)) { if (!documentService.canEdit(document)) {
return "/demo"; return "/view";
} }
model.addAttribute("documentEditParam", documentService.buildDocumentEditParam(userName, userName,filePath)); model.addAttribute("documentEditParam", documentService.buildDocumentEditParam(userName, userName,filePath));
return "/editor"; return "/editor";
} }
@Override
public String viewerDocFile(String fileName, String filePath, String userName, Model model) {
Document document = documentService.getDocument(documentService.buildDocument(filePath, fileName));
model.addAttribute("document", document);
// // 如果该格式不支持编辑,则返回预览页面
// if (!documentService.canEdit(document)) {
// return "/view";
// }
model.addAttribute("documentEditParam", documentService.buildDocumentEditParam(userName, userName,filePath));
return "/view";
}
//编辑文档时回调接口 //编辑文档时回调接口
@Override @Override
public void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException{ public void callBack(HttpServletRequest request, HttpServletResponse response) throws IOException{
...@@ -279,16 +290,11 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -279,16 +290,11 @@ public class LocalFileServiceImpl implements ILocalFileService {
@Override @Override
public Result<?> editKnowledge(Knowledge knowledge) { public Result<?> editKnowledge(Knowledge knowledge) {
Result result = Result.OK(); Result result = Result.OK();
String id = knowledge.getId(); String id = knowledge.getId();
if(id == null || "".equals(id)) if(id == null || "".equals(id))
return Result.error("文章id不能为空"); return Result.error("文章id不能为空");
String publish = EsDateUtil.esFieldDateFormat(knowledge.getPublishDate()); String publish = EsDateUtil.esFieldDateFormat(knowledge.getPublishDate());
knowledge.setPublishDate(publish); knowledge.setPublishDate(publish);
KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo(); KbAuthorizedUser userInfo = SpringContextUtils.getUserInfo();
knowledge.setUpdateBy(userInfo.getName()); knowledge.setUpdateBy(userInfo.getName());
knowledge.setUpdateTime(cn.hutool.core.date.DateUtil.formatDateTime(new Date()).replace(" ", "T")); knowledge.setUpdateTime(cn.hutool.core.date.DateUtil.formatDateTime(new Date()).replace(" ", "T"));
...@@ -299,6 +305,9 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -299,6 +305,9 @@ public class LocalFileServiceImpl implements ILocalFileService {
knowledge.setVerifierId(userInfo.getUserId()); knowledge.setVerifierId(userInfo.getUserId());
knowledge.setVerifierName(userInfo.getUsername()); knowledge.setVerifierName(userInfo.getUsername());
if(Integer.valueOf("0").equals(knowledge.getImportData())){
List<KnowFile> files = knowledge.getFiles(); List<KnowFile> files = knowledge.getFiles();
KnowFile knowFile = files.get(0); KnowFile knowFile = files.get(0);
String filePath = knowFile.getFilePath(); String filePath = knowFile.getFilePath();
...@@ -322,7 +331,12 @@ public class LocalFileServiceImpl implements ILocalFileService { ...@@ -322,7 +331,12 @@ public class LocalFileServiceImpl implements ILocalFileService {
Long size = file.length(); Long size = file.length();
knowFile.setFileSize(size); knowFile.setFileSize(size);
knowledgeService.addKnowledge(knowFile,knowledge,userInfo); knowledgeService.addKnowledge(knowFile,knowledge,userInfo);
}else {
knowledgeService.addKnowledge(null,knowledge,userInfo);
}
return result; return result;
} }
public ResponseEntity<Object> getDoucmentEditStatus(String filePath,String fileName) throws ParseException { public ResponseEntity<Object> getDoucmentEditStatus(String filePath,String fileName) throws ParseException {
String url = officeUrl+officeCommand; String url = officeUrl+officeCommand;
......
...@@ -139,20 +139,21 @@ public class DocUtil { ...@@ -139,20 +139,21 @@ public class DocUtil {
* @throws Exception * @throws Exception
*/ */
public static byte[] convertDocHtml2Doc(String content, Boolean isPage) throws Exception { public static byte[] convertDocHtml2Doc(String content, Boolean isPage) throws Exception {
getLicense(); // getLicense();
if (SystemUtils.IS_OS_LINUX) { // if (SystemUtils.IS_OS_LINUX) {
logger.info("doc set font folder"); // logger.info("doc set font folder");
FontSettings.setFontsFolder(fontsPath, false); // FontSettings.setFontsFolder(fontsPath, false);
} // }
Document doc = new Document(); // Document doc = new Document();
DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream(); // DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream();
DocumentBuilder builder = new DocumentBuilder(doc); // DocumentBuilder builder = new DocumentBuilder(doc);
if (!isPage) // if (!isPage)
content = convertDocHtml2Page(content); // content = convertDocHtml2Page(content);
builder.insertHtml(content); // builder.insertHtml(content);
doc.save(dataByteArrayOutputStream, SaveFormat.DOCX); // doc.save(dataByteArrayOutputStream, SaveFormat.DOCX);
//
return dataByteArrayOutputStream.getData(); // return dataByteArrayOutputStream.getData();
return null;
} }
/** /**
...@@ -160,39 +161,39 @@ public class DocUtil { ...@@ -160,39 +161,39 @@ public class DocUtil {
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static byte[] convertDocHtml2Png(String content, Boolean isPage) throws Exception { // public static byte[] convertDocHtml2Png(String content, Boolean isPage) throws Exception {
getLicense(); // getLicense();
if (SystemUtils.IS_OS_LINUX) { // if (SystemUtils.IS_OS_LINUX) {
logger.info("cover png set font folder"); // logger.info("cover png set font folder");
FontSettings.setFontsFolder(fontsPath, false); // FontSettings.setFontsFolder(fontsPath, false);
} // }
Document doc = new Document(); // Document doc = new Document();
DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream(); // DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream();
DocumentBuilder builder = new DocumentBuilder(doc); // DocumentBuilder builder = new DocumentBuilder(doc);
if (!isPage) // if (!isPage)
content = convertDocHtml2Page(content); // content = convertDocHtml2Page(content);
builder.insertHtml(content); // builder.insertHtml(content);
doc.save(dataByteArrayOutputStream, SaveFormat.PNG); // doc.save(dataByteArrayOutputStream, SaveFormat.PNG);
//
return dataByteArrayOutputStream.getData(); // return dataByteArrayOutputStream.getData();
} // }
public static byte[] convertDocHtml2Pdf(String content, boolean isPage) throws Exception {
getLicense();
if (SystemUtils.IS_OS_LINUX) {
logger.info("pdf set font folder");
FontSettings.setFontsFolder(fontsPath, false);
}
Document doc = new Document();
DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream();
DocumentBuilder builder = new DocumentBuilder(doc);
if (!isPage)
content = convertDocHtml2Page(content);
builder.insertHtml(content);
doc.save(dataByteArrayOutputStream, SaveFormat.PDF);
return dataByteArrayOutputStream.getData(); // public static byte[] convertDocHtml2Pdf(String content, boolean isPage) throws Exception {
} // getLicense();
// if (SystemUtils.IS_OS_LINUX) {
// logger.info("pdf set font folder");
// FontSettings.setFontsFolder(fontsPath, false);
// }
// Document doc = new Document();
// DataByteArrayOutputStream dataByteArrayOutputStream = new DataByteArrayOutputStream();
// DocumentBuilder builder = new DocumentBuilder(doc);
// if (!isPage)
// content = convertDocHtml2Page(content);
// builder.insertHtml(content);
// doc.save(dataByteArrayOutputStream, SaveFormat.PDF);
//
// return dataByteArrayOutputStream.getData();
// }
/** /**
......
package com.zzsn.knowbase.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zzsn.knowbase.entity.KnowledgeExcel;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
public class ExcelExportUtil {
/**
* 读取excel数据
*
* @param firstRow 第一行有用数据(0表示第一行)
* @param columnNum 有用数据的总列数
* @return java.util.List<java.util.List < java.lang.String>>
*/
public static List<List<String>> readExcel(InputStream inputStream, Integer firstRow, Integer columnNum) throws Exception {
List<List<String>> dataList = new ArrayList<>();
//获取整个excel
XSSFWorkbook hb = new XSSFWorkbook(inputStream);
int sheets = hb.getNumberOfSheets();
for (int i = 0; i < sheets; i++) {
XSSFSheet sheet = hb.getSheetAt(i);
//第一行
int firstRowNum = sheet.getFirstRowNum();
//最后一行
int lastRowNum = sheet.getPhysicalNumberOfRows();
for (int j = firstRowNum + firstRow; j < lastRowNum; j++) {
//获取行
XSSFRow row = sheet.getRow(j);
if (row != null) {
List<String> list = new ArrayList<>();
for (int m = 0; m < columnNum; m++) {
String data = ExcelExportUtil.getValue(row.getCell(m)).trim();
list.add(data);
}
dataList.add(list);
}
}
}
return dataList;
}
public static String getValue(XSSFCell xssfCell) {
if (xssfCell == null || xssfCell.toString().trim().equals("")) {
return "";
}
int cellType = xssfCell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(xssfCell)) {
return TimeUtil.getDateString(xssfCell.getDateCellValue());
} else {
//防止数字变成科学计数法的形式
DecimalFormat df = new DecimalFormat("0");
return df.format(xssfCell.getNumericCellValue());
}
} else {
return xssfCell.getStringCellValue();
}
}
public static File getFileDir() {
// 构建上传文件的存放 "文件夹" 路径
String fileDirPath = new String("src/main/resources/static/uploadFiles" );
File fileDir = new File(fileDirPath);
if (!fileDir.exists()) {
// 递归生成文件夹
fileDir.mkdirs();
}
return fileDir;
}
/**
* 导出
* @param data
* @param sheetName
* @param filePath
* @param clazz
* @throws Exception
*/
public static Boolean writeExcelFront(List data, String sheetName, String filePath, Class clazz) throws Exception {
//表头样式
System.out.println("开始写入");
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//内容样式
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置内容靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
int total = data.size();//总数
int max = 50000;//每sheet页允许最大数
int avg = total / max;//sheet页个数
ExcelWriter excelWriter= EasyExcel.write(filePath, clazz).excelType(ExcelTypeEnum.XLSX).registerWriteHandler(horizontalCellStyleStrategy).build();
try{
for (int j = 0; j < avg + 1; j++) {
String sheetnames=sheetName;
int num = j * max;
List dataList1 = new ArrayList<>();
if (StringUtils.isNotBlank(sheetnames)) {
sheetnames = sheetnames + (j + 1);
} else {
sheetnames = j + "";
}
for (int n = num; n < total; n++) {//n即为每个sheet页应该开始的数
if(n>=num+50000){
break;
}
dataList1.add(data.get(n));//从总的list数据里面取出该处于哪个sheet页的数据,然后加进exportList,exportList即为当前sheet页应该有的数据
}
WriteSheet writeSheet = EasyExcel.writerSheet(j, sheetnames).build();
excelWriter.write(dataList1,writeSheet);
}
}finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
System.out.println("写入完成");
return true;
}
public static void download(HttpServletResponse response, String filePath, boolean delete) throws UnsupportedEncodingException {
File file = new File(filePath);
if (file.exists()) {
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf8"));
//加上设置大小 下载下来的excel文件才不会在打开前提示修复
response.addHeader("Content-Length", String.valueOf(file.length()));
byte[] buffer = new byte[1024];
//输出流
OutputStream os = null;
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
os.flush();
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (delete) {
//文件下载结束后,删除上传到项目的文件
file.delete();
}
}
}
}
...@@ -33,6 +33,7 @@ public class KnowledgeVO { ...@@ -33,6 +33,7 @@ public class KnowledgeVO {
private String author; private String author;
private Integer score; private Integer score;
private Integer verifyStatus; private Integer verifyStatus;
private Integer importData;
private List<Content> contents; private List<Content> contents;
private List<KnowFile> files; private List<KnowFile> files;
......
...@@ -41,20 +41,24 @@ $(function () { ...@@ -41,20 +41,24 @@ $(function () {
}; };
var getDocument = function () { var getDocument = function () {
var title = document.title;
var storage = document.storage
var URL = document.URL
var url = URL.replace("viewer", "download");
// 文件名(此处先从连接参数中获取,方便调试) // 文件名(此处先从连接参数中获取,方便调试)
var fileName = getUrlParam('file'); // var fileName = getUrlParam('file');
//console.log(fileName); //console.log(fileName);
!fileName && (fileName = "doc.doc"); // !fileName && (fileName = "doc.doc");
//console.log(fileName); //console.log(fileName);
// 文件类型(扩展名) // 文件类型(扩展名)
var ext = fileName.substr(fileName.lastIndexOf(".") + 1); var ext = title.substr(title.lastIndexOf(".") + 1);
return { return {
"document": { "document": {
"fileType": ext, "fileType": ext,
"key": "sherlocky_oss_office_" + new Date().getMilliseconds() + "_" + fileName, // 不同文件key必须唯一 "key": "sherlocky_oss_office_" + new Date().getMilliseconds() + "_" + ext, // 不同文件key必须唯一,不能有中文
"title": "测试文档" + fileName, "title": title, //"测试文档" + fileName,
"url": "http://192.168.0.58:20053//download" "url": url //"http://192.168.1.75:9088/api/file/download?fileName=aaa.docx&filePath=20240117/24011700012138.docx"
} }
}; };
}; };
...@@ -74,8 +78,7 @@ $(function () { ...@@ -74,8 +78,7 @@ $(function () {
config.editorConfig = { config.editorConfig = {
//"actionLink": ACTION_DATA, //"actionLink": ACTION_DATA,
// edit时必须的字段 // edit时必须的字段
"callbackUrl": "http://10.4.89.60:8080/api/callback", "callbackUrl": "http://192.168.1.75:4000/callback",
//"createUrl": "https://example.com/url-to-create-document/",
"lang": "zh-CN",//"en-US", "lang": "zh-CN",//"en-US",
"mode": "view",//"edit", "mode": "view",//"edit",
"recent": [ "recent": [
......
var Viewer = function() {
var docEditor;
var innerAlert = function (message) {
if (console && console.log)
console.log(message);
};
var onAppReady = function () {
innerAlert("文档查看已就绪~");
};
var onDocumentStateChange = function (event) {
var title = document.title.replace(/\*$/g, "");
document.title = title + (event.data ? "*" : "");
};
var onError = function (event) {
if (event) {
innerAlert(event.data);
}
};
var onOutdatedVersion = function (event) {
location.reload(true);
};
var getUrlParam = function (name) {
//构造一个含有目标参数的正则表达式对象
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
//匹配目标参数
var r = window.location.search.substr(1).match(reg);
//返回参数值
if (r != null) {
return decodeURI(r[2]);
}
return null;
};
var getDocumentConfig = function (document) {
if (document) {
return {
"document": document
};
}
innerAlert("文档未指定!");
return null;
};
var сonnectEditor = function (document) {
var config = getDocumentConfig(document);
config.width = "100%";
config.height = "100%";
config.events = {
"onAppReady": onAppReady,
"onDocumentStateChange": onDocumentStateChange,
"onError": onError,
"onOutdatedVersion": onOutdatedVersion
};
config.editorConfig = {
"lang": "zh-CN",
"mode": "view",
"recent": [],
// 自定义一些配置
"customization": {
"chat": false, // 禁用聊天菜单按钮
"commentAuthorOnly": true, // 仅能编辑和删除其注释
"comments": false, // 隐藏文档注释菜单按钮
"compactHeader": false, // 隐藏附加操作按钮
"compactToolbar": false, // 完整工具栏(true代表紧凑工具栏)
"feedback": {
"visible": false // 隐藏反馈按钮
},
"forcesave": false, // true 表示强制文件保存请求添加到回调处理程序
"goback": false,/*{
"blank": true, // 转到文档时,在新窗口打开网站(false表示当前窗口打开)
"text": "转到文档位置(可以考虑放文档打开源页面)",
// 文档打开失败时的跳转也是该地址
"url": "http://www.lezhixing.com.cn"
},*/
"help": false, // 隐藏帮助按钮
"hideRightMenu": false, // 首次加载时隐藏右侧菜单(true 为显示)
"showReviewChanges": false, // 加载编辑器时自动显示/隐藏审阅更改面板(true显示 false隐藏)
"toolbarNoTabs": false, // 清楚地显示顶部工具栏选项卡(true 代表仅突出显示以查看选择了哪一个)
"zoom": 100 // 定义文档显示缩放百分比值
}
};
docEditor = new DocsAPI.DocEditor("iframeEditor", config);
};
return {
init : function(document) {
сonnectEditor(document);
}
}
}();
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
This is a page
</body>
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="zh-CN">
<head>
<title th:text="${document.title}"></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" th:href="@{/css/viewer.css}">
</head>
<body>
<div class="form">
<div id="iframeEditor"></div>
</div>
<script type="text/javascript" th:src="@{/js/jquery-1.8.2.js}"></script>
<script type="text/javascript" th:src="@{${documentServerApiJs}}"></script>
<script type="text/javascript" th:src="@{/js/demo.js}"></script>
<!-- 先通过 th:inline=“javascript” 添加到标签,这样js代码即可访问model中的属性 -->
<script th:inline="javascript">
// js 中可以通过“[[${xxx}]]” 格式获得实际的值
Editor.init([[${document}]], [[${documentEditParam}]]);
</script>
</body>
</html>
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论