table.getn(tableName) 的用法注意。

转自:http://blog.sina.com.cn/s/blog_4a2e9af90100cv1z.html

 

 

1.table.getn(tableName)       

--等同于操作符 #

 

作用:得到一个table的大小。

注意:该table的key必须是有序的,索引是从1开始的。

 

例如:

a)有序table:

local table1 = {10, 20, 30, 50, 1000};

用table.getn(table1) 或 #table1 得到 5。

 

b) 无序table:

local table2 = {

    ["bb"] = 1,

    ["cc"] = 2,

    ["dd"] = 3,

    ["ee"] = nil,

    ["ff"] = 4,

}

用table.getn(table2) 或 #table2  无法得到正确的大小。

 

这种table如果想得到大小一般我这样做:

local count = 0

for k,v in pairs(table2) do

    count = count + 1

end

package org.example.databaseword.util; import com.itextpdf.kernel.colors.ColorConstants; import com.itextpdf.kernel.font.PdfFont; import com.itextpdf.kernel.font.PdfFontFactory; import com.itextpdf.kernel.pdf.PdfDocument; import com.itextpdf.kernel.pdf.PdfWriter; import com.itextpdf.layout.Document; import com.itextpdf.layout.element.*; import com.itextpdf.layout.properties.TabAlignment; import com.itextpdf.layout.properties.TextAlignment; import com.itextpdf.layout.properties.UnitValue; import jakarta.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.example.databaseword.entity.Catalogue; import org.example.databaseword.mapper.TableMapper; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.*; import java.util.List; @Slf4j @Component public class TableUtil { @Resource TableMapper tableMapper; // 配置常量 private static final float[] TABLE_COLUMN_WIDTHS = {1, 2, 1, 1, 1, 2}; private static final String[] TABLE_HEADERS = {"字段名", "类型", "长度", "NULL", "默认值", "注释"}; public void toPdf(List<Map<String, Object>> tables, String fileName, String title) { validateParameters(tables, fileName, title); try (PdfWriter writer = new PdfWriter(fileName); PdfDocument pdf = new PdfDocument(writer); Document document = new Document(pdf)) { // 初始化字体 PdfFont contentFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H"); // 添加封面页 addCoverPage(document, title, contentFont); //预生成目录数据 List<Catalogue> tocEntries = preGenerateTocEntries(tables); //在封面后插入目录 insertTableOfContents(document, tocEntries); // 生成表结构内容 generateTableContentWithToc(document, tables, contentFont); log.info("PDF生成成功: {}", fileName); } catch (IOException e) { log.error("PDF生成失败", e); throw new RuntimeException("PDF生成失败: " + e.getMessage(), e); } } // 预生成目录条目 private List<Catalogue> preGenerateTocEntries(List<Map<String, Object>> tables) { List<Catalogue> entries = new ArrayList<>(); int currentPage = 3; // 封面(1) + 目录(2) = 内容从第3页开始 for (Map<String, Object> tableMap : tables) { String tableName = getStringValue(tableMap, "TABLE_NAME"); String tableComment = getStringValue(tableMap, "TABLE_COMMENT"); entries.add(new Catalogue(tableName + (tableComment.isEmpty() ? "" : " (" + tableComment + ")"), currentPage )); } return entries; } //在封面后添加目录 private void insertTableOfContents(Document document, List<Catalogue> tocEntries) throws IOException { PdfFont CatalogueTitleFont = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H"); // 添加目录标题 Paragraph tocTitle = new Paragraph("目录") .setFont(CatalogueTitleFont) .setFontSize(16) .setBold() .setTextAlignment(TextAlignment.CENTER) .setMarginBottom(20); document.add(tocTitle); // 添加目录内容 for (Catalogue entry : tocEntries) { Paragraph tocItem = new Paragraph() .add(entry.getTitle()) .addTabStops(new TabStop(500, TabAlignment.RIGHT)) .add(new Tab()) .add(String.valueOf(entry.getPageNumber())) .setMarginBottom(5); document.add(tocItem); } document.add(new AreaBreak()); } /* * 生成表内容 */ private void generateTableContentWithToc(Document document, List<Map<String, Object>> tables, PdfFont contentFont) { int pageNum = 3; for (Map<String, Object> tableMap : tables) { String tableName = getStringValue(tableMap, "TABLE_NAME"); String tableComment = getStringValue(tableMap, "TABLE_COMMENT"); // 添加表标题 addTableTitle(document, tableName, tableComment, contentFont); // 创建并填充表格 Table pdfTable = createTableWithHeader(contentFont); fillTableContent(pdfTable, tableName, contentFont); document.add(pdfTable); } } /** * 验证输入参数 */ private void validateParameters(List<Map<String, Object>> tables, String fileName, String title) { Objects.requireNonNull(tables, "表信息列表不能为null"); Objects.requireNonNull(fileName, "文件名不能为null"); Objects.requireNonNull(title, "标题不能为null"); if (tables.isEmpty()) { throw new IllegalArgumentException("表信息列表不能为空"); } if (fileName.trim().isEmpty()) { throw new IllegalArgumentException("文件名不能为空"); } } /** * 添加封面页 */ private void addCoverPage(Document document, String title, PdfFont titleFont) { Paragraph titleParagraph = new Paragraph(title) .setFont(titleFont) .setFontSize(24) .setTextAlignment(TextAlignment.CENTER) .setMarginBottom(20); document.add(titleParagraph); document.add(new Paragraph("\n")); // 添加空行 document.add(new AreaBreak()); } /** * 添加表标题 */ private void addTableTitle(Document document, String tableName, String tableComment, PdfFont font) { Paragraph tableTitle = new Paragraph("表名: " + tableName + " (" + tableComment + ")") .setFont(font) .setFontSize(12) .setTextAlignment(TextAlignment.CENTER) .setMarginBottom(10); document.add(tableTitle); } /** * 创建带表头的表格 */ private Table createTableWithHeader(PdfFont headerFont) { Table table = new Table(UnitValue.createPercentArray(TABLE_COLUMN_WIDTHS)); table.setWidth(UnitValue.createPercentValue(100)); // 添加表头 for (String header : TABLE_HEADERS) { Cell cell = new Cell() .add(new Paragraph(header).setFont(headerFont).setFontSize(10)) .setBackgroundColor(ColorConstants.LIGHT_GRAY) .setTextAlignment(TextAlignment.CENTER); table.addHeaderCell(cell); } return table; } /** * 填充表格内容 */ private void fillTableContent(Table table, String tableName, PdfFont contentFont) { List<Map<String, Object>> fields = getTable(tableName); for (Map<String, Object> field : fields) { table.addCell(createContentCell(getStringValue(field, "COLUMN_NAME"), contentFont)); table.addCell(createContentCell(getStringValue(field, "DATA_TYPE"), contentFont)); table.addCell(createContentCell(getStringValue(field, "CHARACTER_MAXIMUM_LENGTH"), contentFont)); table.addCell(createContentCell(getStringValue(field, "IS_NULLABLE"), contentFont)); table.addCell(createContentCell(getStringValue(field, "COLUMN_DEFAULT"), contentFont)); table.addCell(createContentCell(getStringValue(field, "COLUMN_COMMENT"), contentFont)); } } /** * 安全获取字符串值 */ private String getStringValue(Map<String, Object> map, String key) { Object valueObj = map.getOrDefault(key, ""); return valueObj instanceof String ? (String) valueObj : (valueObj == null ? "" : valueObj.toString()); } /** * 从数据库中获取表字段信息 */ private List<Map<String, Object>> getTable(String tableName) { try { return tableMapper.getTable(tableName); } catch (Exception e) { log.error("查询表结构失败: {}", tableName, e); throw new RuntimeException("查询表结构失败: " + tableName, e); } } /** * 创建内容单元格 */ private Cell createContentCell(String text, PdfFont font) { return new Cell() .add(new Paragraph(text).setFont(font).setFontSize(9)) .setTextAlignment(TextAlignment.CENTER); } } 在我的代码中使用除了封面页和目录页每页添加页码然后用每个表的表名去判断当前页码然后生成目录页码
最新发布
06-19
package com.ever.digitalfactory.ppm.usage.rabbitmq.impl; import com.ever.beeboat.runtime.config.exception.AppError; import com.ever.beeboat.runtime.config.exception.AppErrorException; import com.ever.common.util.BpmUtils; import com.ever.common.util.UserTokenUtils; import com.ever.digitalfactory.ppm.base.consts.PpmConsts; import com.ever.digitalfactory.ppm.usage.adapter.BasicAdapter; import com.ever.digitalfactory.ppm.usage.adapter.SysAdapter; import com.ever.digitalfactory.ppm.usage.adapter.param.ManufacturingBomSonIsLackMaterialsUpdateParam; import com.ever.digitalfactory.ppm.usage.enums.OutputStatusEnum; import com.ever.digitalfactory.ppm.usage.enums.YesOrNoEnum; import com.ever.digitalfactory.ppm.usage.productionexecute.dao.PpmAssembleOutputTaskDao; import com.ever.digitalfactory.ppm.usage.productionexecute.domain.PpmAssembleOutputMaterial; import com.ever.digitalfactory.ppm.usage.productionexecute.domain.PpmAssembleOutputSelfCheck; import com.ever.digitalfactory.ppm.usage.productionexecute.domain.PpmAssembleOutputTask; import com.ever.digitalfactory.ppm.usage.productionexecute.service.PpmAssembleOutputMaterialService; import com.ever.digitalfactory.ppm.usage.productionexecute.service.PpmAssembleOutputSelfCheckService; import com.ever.digitalfactory.ppm.usage.productionexecute.service.PpmAssembleOutputTaskService; import com.ever.digitalfactory.ppm.usage.rabbitmq.ApprovalParamEntity; import com.ever.digitalfactory.ppm.usage.rabbitmq.enums.MqStatusEnum; import com.ever.digitalfactory.ppm.usage.rabbitmq.enums.MqTypeEnum; import com.ever.digitalfactory.ppm.usage.rabbitmq.factory.ConsumeFlowMessage; import com.ever.digitalfactory.system.commons.component.Resume; import com.ever.digitalfactory.system.commons.sys.param.SystemResumeSaveListBatchParam; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static com.ever.digitalfactory.ppm.usage.enums.OutputStatusEnum.SOLD_TASK; /** * 销项送审回调接口 */ @Slf4j @Service @RefreshScope public class CheckOutputTaskToMaterialAndSelfCheckResult implements ConsumeFlowMessage { @Resource @Lazy private PpmAssembleOutputTaskService assembleOutputTaskService; @Resource @Lazy private SysAdapter sysAdapter; @Resource @Lazy private PpmAssembleOutputSelfCheckService assembleOutputSelfCheckService; @Resource @Lazy private PpmAssembleOutputMaterialService assembleOutputMaterialService; @Resource @Lazy private PpmAssembleOutputTaskDao assembleOutputTaskDao; @Resume(tableName = PpmConsts.ProductionExecute.PpmAssembleOutputTask.TABLE) @Override public void dealBusinessByApproveResult(ApprovalParamEntity approvalParam) { PpmAssembleOutputTask outputTask = assembleOutputTaskService.getById(approvalParam.getBizId()); if (outputTask == null) { throw new AppErrorException(AppError.INTERNAL_ERROR.getCode(), "数据不存在"); } //审批通过 if (MqStatusEnum.AGREE.getCode().equals(approvalParam.getActionCode())) { assembleOutputTaskDao.updateOutputStatus(YesOrNoEnum.YES.getCode(),outputTask.getId()); List<PpmAssembleOutputMaterial> outputMaterialList = assembleOutputMaterialService.lambdaQuery() .eq(PpmAssembleOutputMaterial::getAssembleOutputTaskId, outputTask.getId()) .eq(PpmAssembleOutputMaterial::getIsDel, YesOrNoEnum.NO.getCode()) .eq(PpmAssembleOutputMaterial::getBranchCompanyId, outputTask.getBranchCompanyId()) .list(); //更新mbom的缺料数量以及是否缺料状态 assembleOutputTaskDao.batchUpdateLackMaterials(outputMaterialList.stream() .map(PpmAssembleOutputMaterial::getMbomSonId) // 提取字段 .collect(Collectors.toList()),String.valueOf(YesOrNoEnum.NO.getCode()),YesOrNoEnum.NO.getCode()); List<PpmAssembleOutputMaterial> upmaterialList = outputMaterialList.stream().map(m -> { m.setIsLackMaterials(YesOrNoEnum.NO.getCode()); m.setLackItemNum(YesOrNoEnum.NO.getCode()); return m; }).collect(Collectors.toList()); List<PpmAssembleOutputSelfCheck> outputSelfCheckList = assembleOutputSelfCheckService.lambdaQuery() .eq(PpmAssembleOutputSelfCheck::getAssembleOutputTaskId, outputTask.getId()) .eq(PpmAssembleOutputSelfCheck::getIsDel, YesOrNoEnum.NO.getCode()) .eq(PpmAssembleOutputSelfCheck::getBranchCompanyId, UserTokenUtils.getBranchCompanyId()) .list(); List<PpmAssembleOutputSelfCheck> upoutputSelfCheckList = outputSelfCheckList.stream().map(m -> { m.setCheckResult(YesOrNoEnum.NO.getCode()); return m; }).collect(Collectors.toList()); //更新销项物料表 assembleOutputMaterialService.updateBatchById(upmaterialList); //更新销项检验表 assembleOutputSelfCheckService.updateBatchById(upoutputSelfCheckList); } //被驳回 if (MqStatusEnum.REJECT.getCode().equals(approvalParam.getActionCode())) { SystemResumeSaveListBatchParam param = BpmUtils.saveSystemResume(new ArrayList<>(Arrays.asList(approvalParam.getBizId())), approvalParam, MqStatusEnum.REJECT.getMsg(), MqTypeEnum.ASSEMBLE_OUTPUT_TASK_APPROVE.getMsg()); try { sysAdapter.saveResumeListBatch(param); } catch (Exception e) { log.error("履历保存操作失败!"); } } //撤回 改回送审之前的状态 if (MqStatusEnum.REVOKE.getCode().equals(approvalParam.getActionCode())) { SystemResumeSaveListBatchParam param = BpmUtils.saveSystemResume(new ArrayList<>(Arrays.asList(approvalParam.getBizId())), approvalParam, MqStatusEnum.REJECT.getMsg(), MqTypeEnum.ASSEMBLE_OUTPUT_TASK_APPROVE.getMsg()); try { sysAdapter.saveResumeListBatch(param); } catch (Exception e) { log.error("履历保存操作失败!"); } } //中间节点通过 if (MqStatusEnum.NODE_AGREE.getCode().equals(approvalParam.getActionCode())) { SystemResumeSaveListBatchParam param = BpmUtils.saveSystemResume(new ArrayList<>(Arrays.asList(approvalParam.getBizId())), approvalParam, MqStatusEnum.REJECT.getMsg(), MqTypeEnum.ASSEMBLE_OUTPUT_TASK_APPROVE.getMsg()); try { sysAdapter.saveResumeListBatch(param); } catch (Exception e) { log.error("履历保存操作失败!"); } } //修改审批人 if (MqStatusEnum.MODIFY_APPROVER.getCode().equals(approvalParam.getActionCode())) { SystemResumeSaveListBatchParam param = BpmUtils.saveSystemResume(new ArrayList<>(Arrays.asList(approvalParam.getBizId())), approvalParam, MqStatusEnum.REJECT.getMsg(), MqTypeEnum.ASSEMBLE_OUTPUT_TASK_APPROVE.getMsg()); try { sysAdapter.saveResumeListBatch(param); } catch (Exception e) { log.error("履历保存操作失败!"); } } } } 这段代码为什么第一次执行的时候会漏掉 assembleOutputTaskDao.updateOutputStatus(YesOrNoEnum.YES.getCode(),outputTask.getId());这个和 assembleOutputSelfCheckService.updateBatchById(upoutputSelfCheckList);这个不执行
06-18
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值