目录
1.字符串取中对调
/* 编码后的字符串(前后两部分交换) */
public static String codeEncode(String code){
int floor = Math.floorDiv(code.length(),2);
return code(code, floor);
}
/* 解码后的原始字符串(前后两部分恢复原顺序) */
public static String codeDecode(String code){
int ceil = Math.floorDiv(code.length(),2);
ceil = ceil + (code.length() % 2);
return code(code, ceil);
}
private static String code(String code, int middle){
String firstPart = code.substring(0, middle);
String secondPart = code.substring(middle);
return secondPart+firstPart;
}
2.字符串编码解码
// 字符串去重
Set<String> list = new HashSet<>();
String[] split = a.split("");
for (String item : split) {
list.add(item);
}
a = String.join("", list);
System.out.println(a);
public static final String fixString= "....";
// 对输入的字符串编码
public static String infoEncode(String info){
String[] hanzis = info.split("");
StringBuilder newInfo = new StringBuilder();
for (String item:hanzis) {
int i = random.nextInt(fixString.length()-1);
char c = fixString.charAt(i);//获取随机位置的汉字
newInfo.append(item).append(c);
}
return newInfo .toString();
}
// 解码
public static String infoDecode(String info){
String[] split = info.split("");
String newInfo = "";
for (int i = 0; i < split.length; i++) {
if (i % 2 == 0) {
newInfo += split[i];
}
}
return newInfo ;
}
3.递归
打印传入数字的每一位
// 打印传入数字的每一位 1234-->1 2 3 4
public static void print1(int num){
if (num < 10){
System.out.println(num + "");
return ;
}
print1(num/10);
System.out.println(num%10 + "");
}
// 打印传入数字的每一位 1234-->1 2 3 4
public static void print2(int num){
if (num > 9){
print2(num/10);
}
System.out.println(num%10 + "");
}
求和
// 求和 1 + 2 + 3 + ... + 10
public static int sum(int num){
if (num == 0){
return 0;
}
return num + sum(num-1);
}
n!
// n!
public static int jieChen(int num){
if (num == 0 || num ==1){
return 1;
}
return num * jieChen(num - 1);
}
4.postman添加token
①. token配置
②. 测试
5.word文件导入功能
1.工具类WordUtil
package com.ydlh.common.utils.poi;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.plugin.table.MultipleRowTableRenderPolicy;
import com.ydlh.common.annotation.Word;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ResourceUtils;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
@Slf4j
public class WordUtil {
private static String path="classpath:template"+File.separator+"word"+File.separator;
public static void exportWord(String templateName,Object params, OutputStream outputStream){
XWPFTemplate template = null;
try {
ResourcePatternResolver batchLoader = new PathMatchingResourcePatternResolver();
Resource resource = batchLoader.getResource(path + templateName);
// File file = resource.getFile();
// 循环行表格锁定函数
ConfigureBuilder builder = Configure.builder().useSpringEL();
initTableRenderPolicy(builder,params.getClass());
template = XWPFTemplate.compile(resource.getInputStream(),builder.build()).render(params);
try {
template.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}catch (FileNotFoundException e){
throw new RuntimeException("file["+path + templateName+"] not found",e);
}catch (IOException e){
throw new RuntimeException("generic word file fail",e);
}finally {
try {
if (template != null){
template.close();
}
} catch (IOException e1) {
log.warn("XWPFTemplate close exception",e1);
}
}
}
/**
* 初始化表格策略
*/
private static ConfigureBuilder initTableRenderPolicy(ConfigureBuilder builder,Class cls)
{
Map<Field, Word> fieldWordMap = genericWordField(cls);
Set<Map.Entry<Field, Word>> entries = fieldWordMap.entrySet();
for (Map.Entry<Field, Word> entry : entries) {
Field key = entry.getKey();
Word value = entry.getValue();
Word.TableType type = value.type();
if (type == Word.TableType.Row){
String name = key.getName();
LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();
builder.bind(name,loopRowTableRenderPolicy);
}
if (type == Word.TableType.Column){
String name = key.getName();
LoopColumnTableRenderPolicy loopColumnTableRenderPolicy = new LoopColumnTableRenderPolicy();
builder.bind(name,loopColumnTableRenderPolicy);
}
if (type == Word.TableType.MultipleRow){
String name = key.getName();
MultipleRowTableRenderPolicy multipleRowTableRenderPolicy = new MultipleRowTableRenderPolicy();
builder.bind(name,multipleRowTableRenderPolicy);
}
}
return builder;
}
/**
* 得到所有定义字段
*/
private static Map<Field, Word> genericWordField(Class cls)
{
Map<Field, Word> wordFieldMap = new HashMap<>();
List<Field> tempFields = new ArrayList<>();
tempFields.addAll(Arrays.asList(cls.getSuperclass().getDeclaredFields()));
tempFields.addAll(Arrays.asList(cls.getDeclaredFields()));
for (Field field : tempFields)
{
// 单注解
if (field.isAnnotationPresent(Word.class))
{
wordFieldMap.put(field,field.getAnnotation(Word.class));
}
}
return wordFieldMap;
}
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\奎\\Desktop\\temp\\temp2.docx");
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
Data data = new Data();
Row row = new Row();
row.setMaterialName("setMaterialName");
row.setSpecification("setSpecification");
row.setRkDate("setRkDate");
row.setCompanyName("setCompanyName");
row.setNum("setNum");
Row row3 = new Row();
row3.setMaterialName("setMaterialName1");
row3.setSpecification("setSpecification2");
row3.setRkDate("setRkDate3");
row3.setCompanyName("setCompanyName4");
row3.setNum("setNum5");
data.setRowTables(Arrays.asList(row,row3));
exportWord("rk_dkjj.docx",data,fileOutputStream);
fileOutputStream.close();
}
@lombok.Data
public static class Data{
private String name;
private String age;
private String phone;
private String sex;
@Word(type = Word.TableType.MultipleRow)
private List<Rows> mulTables;
@Word(type = Word.TableType.Row)
private List<Row> rowTables;
@Word(type = Word.TableType.Column)
private List<Col> colTables;
}
@lombok.Data
public static class Item{
private String a;
private String b;
private String c;
}
@lombok.Data
public static class Row{
private String materialName;
private String rkDate;
private String specification;
private String companyName;
private String num;
private String remark;
}
@lombok.Data
public static class Col{
private String count;
private String name;
private String remark;
}
@lombok.Data
public static class Rows{
private String stationName;
private String stationCode;
private String address;
private String text1;
private String text2;
}
}
2.导出类响应字段
@Data
public class BizTorrentialFloodStationImportVo {
@Excel(name = "编码",type = Excel.Type.ALL,prompt="必输")
private String stationCode;
@Excel(name = "年月日",type = Excel.Type.ALL, dateFormat = "yyyy-MM-dd")
private Date stationCreateDate;
@Excel(name = "状况",type = Excel.Type.ALL,combo={"good","breakdown","stop"})
private String runStatus;
}
3.导入模板
// 导出类的基础上设置模板
@GetMapping("/importTemplate")
public void importTemplate(){
ExcelUtil<BizTorrentialFloodStationImportVo> util =
new ExcelUtil<BizTorrentialFloodStationImportVo>(BizTorrentialFloodStationImportVo.class);
List<BizTorrentialFloodStationImportVo> objects = new ArrayList<>();
objects.add(new BizTorrentialFloodStationImportVo());
util.exportExcel(objects,"数据");
}
4.上传及新增
@PostMapping("/torrentialFloodUpload")
@Operation(summary = "文件上传")
@Log(title = "文件上传", businessType = BusinessType.IMPORT)
@Parameter(name = "file", description = "文件")
public AjaxResult upload(@RequestBody MultipartFile file) throws Exception {
// 表格存储的集合
List<BizTorrentialFloodStation> bizTorrentialFloodStationList = new ArrayList<>();
ExcelUtil<BizTorrentialFloodStationImportVo> excelUtil =
new ExcelUtil(BizTorrentialFloodStationImportVo.class);
List<BizTorrentialFloodStationImportVo> dataVos = excelUtil.importExcel(file.getInputStream());
for (BizTorrentialFloodStationImportVo item : dataVos) {
BizTorrentialFloodStation bizTorrentialFloodStation = new BizTorrentialFloodStation();
String codeDecode = YdlhUtil.codeEncode(item.getStationCode());
String nameDecode = YdlhUtil.nameEncode(item.getStationName());
item.setStationName(nameDecode);
item.setStationCode(codeDecode);
BeanUtils.copyProperties(item,bizTorrentialFloodStation);// 属性字段复制
bizTorrentialFloodStationList.add(bizTorrentialFloodStation);
}
iBizTorrentialFloodStationService.saveBatch(bizTorrentialFloodStationList);
return success(bizTorrentialFloodStationList);
}
5.页面设置
<el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
<el-dialog title="文件上传" :visible.sync="upload.open" width="400px" append-to-body>
<el-upload ref="upload"
:limit="1" // 最大允许上传个数
accept=".xlsx, .xls" //接受上传的文件类型
:action="upload.url" // 必选参数,上传的地址
:disabled="upload.isUploading"// 是否禁用
:on-progress="handleFileUploadProgress" // 文件上传时的钩子
:on-success="handleFileSuccess" //文件上传成功时的钩子
:auto-upload="false" // 是否在选取文件后立即进行上传
drag //是否启用拖拽上传
:headers="upload.headers"//token>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip text-center" slot="tip">
<span>仅允许导入xls、xlsx格式文件。</span>
<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
@click="getExportTemplate">下载模板</el-link>
</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitFileForm">确 定</el-button>
<el-button @click="upload.open = false">取 消</el-button>
</div>
</el-dialog>
<script>
import { getToken } from "@/utils/auth";
import { importTemplate } from "@/api/biz/torrentialflood";
export default {
data() {
return {
upload: {
open: false,
isUploading: false,
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/biz/torrentialflood/torrentialFloodUpload",
// 设置上传的请求头部
headers: { Authorization: "Bearer " + getToken() },
},
};
},
methods: {
/** 导入按钮操作 */
handleImport() {
this.upload.open = true;
},
/** 下载模板操作 */
getExportTemplate() {
importTemplate();
},
// 文件上传中处理
handleFileUploadProgress(event, file, fileList) {
this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
this.upload.isUploading = false;
this.upload.open = false;
this.$refs.upload.clearFiles();
this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
this.getList();
},
// 提交上传文件
submitFileForm() {
this.$refs.upload.submit();
},
},
};
</script>
import request from "@/utils/request";
import {downloadGet} from "@/utils/request"
// 下载用户导入模板
export function importTemplate(query) {
return downloadGet("/biz/torrentialflood/importTemplate",null,"山洪监测站数据.xlsx")
}
6.word文件导出功能
可借鉴导入模版
@Log(title = "数据", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('biz:waterResourceStat:export')")
@GetMapping("/export")
public void export(BizWaterResourceStatQueryDto dto){
ExcelUtil<BizWaterResourceStatDto> util = new ExcelUtil<>(BizWaterResourceStatDto.class);
List<BizWaterResourceStatDto> bizWaterResourceStatDtos = iBizWaterResourceStatService.selectData(dto);
util.exportExcel(bizWaterResourceStatDtos, "数据");
}
7 flag
// 查询出所有a对应的物资,物资状态都不为‘待上架’时,a的状态设置为‘已上架’
LambdaQueryWrapper<WmsStock> rkDetailLambdaQueryWrapper =new LambdaQueryWrapper<>();
rkDetailLambdaQueryWrapper.eq(WmsStock::getA, A.getId());
List<WmsStock> wmsRkDetailList = stockService.list(rkDetailLambdaQueryWrapper);
wmsRkDetailList.removeAll(B);//当前接口内容中,存在对WmsStock表的操作,需要过滤这个集合,如果没有可以忽略
boolean complateFlag = true;
for (WmsStock detail : wmsRkDetailList) {
String status = detail.getStatus();
if (StringUtils.equals(status,待上架)){
complateFlag = false;
break;
}
}
if (complateFlag){
a.setRkStatus(已上架);
aService.updateById(A);
}
8.两表联查,获取列表
// 不使用sql
List<WmsCk> ckList = iWmsCkService.list();
List<Long> ckIds = ckList.stream().map(WmsCk::getId).collect(Collectors.toList());
Map<Long, List<WmsCkDetail>> ckDetailMap = iWmsCkDetailService.list(
new LambdaQueryWrapper<WmsCkDetail>().in(WmsCkDetail::getCkId, ckIds))
.stream()
.collect(Collectors.groupingBy(WmsCkDetail::getCkId));
List<WmsCkDetail> ckDetailList = ListUtil.createList();
ckList.stream().forEach(ck -> {
ck.setCkDetailList(ckDetailMap.getOrDefault(ck.getId(), ckDetailList));
});
9.图片插入到word
1.使用POI将图片插入到word
// 创建文件: 创建文档上面设置图片, 读取图片输入流写入文件
File file = new File("E:\\table.docx");//创建word文件名
file.createNewFile();
XWPFDocument document = new XWPFDocument();//创建一篇文档
XWPFParagraph paragraph = document.createParagraph();//文档中创建段落(可以有多个文本块)
XWPFRun run = paragraph.createRun();//创建一个文本块
String imgFile = "D:\\hhycjh2\\photo\\flood3.png";//上传图片的绝对路径
FileInputStream fileInputStream = new FileInputStream(imgFile);//读取图片转换流
run.addPicture(fileInputStream, XWPFDocument.PICTURE_TYPE_PNG,
imgFile, Units.toEMU(20), Units.toEMU(20));//文本块中设置流,图片类型,绝对路径,emu大小
FileOutputStream fileOutputStream = new FileOutputStream(file);//将流的内容写入到table.docx文件中
document.write(fileOutputStream);//输入文件
fileOutputStream.close();//关闭流
document.close();
2.使用POI将图片插入到word的表格当中
// 直接再文档上面设置表格 在添加图片
XWPFDocument document = new XWPFDocument();
XWPFTable table = document.createTable(1, 2); // 创建一个1行2列的表格
XWPFTableRow row = table.getRow(0); // 获取第一行
XWPFTableCell cell = row.getCell(0); // 获取第一个单元格
cell.setText("图片"); // 设置单元格文本
XWPFParagraph paragraph = cell.addParagraph(); // 在单元格中添加段落
XWPFRun run = paragraph.createRun();
String imgFile = "D:\\hhycjh2\\photo\\flood3.png";
run.addPicture(new FileInputStream(imgFile), XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(200), Units.toEMU(200)); // 在段落中添加图片
FileOutputStream out = new FileOutputStream(写入的文件);
document.write(out);
out.close();
document.close();