改ページ

参照

Controllerクラス内で、StandardSetControllerを作成したら
setPageSize()で1ページあたりに表示する最大レコード数をセットします。
next()で次のページへ、
previous()で前のページへ、
first()で最初のページへ、
last()で最後のページへ、
getHasNext()で次のページがあるかどうかを取得、
getHasPrevious()で前のページがあるかどうかを取得、
getPageNumber()で現在のページ番号を取得、
getResultSize()で総レコード数を取得

public ApexPages.StandardSetController setCon { get; set; }

 setCon = new ApexPages.StandardSetController(Database.getQueryLocator([select id from object__c where id in:ids]));   			
	    	// 画面サイズ
	    	setCon.setPageSize(PAGESIZE);
	    	system.debug('=========plantList========'+plantList);
	    	makeDisClass((List<PlantApply__c>)setCon.getRecords());

/*
    * 最初のページへ
    */
    public void getfirst(){
    	setCon.first();
    	makeDisClass( (List<PlantApply__c>)setCon.getRecords() );
    }
	
	/*
    * 前のページへ
    */
    public void getPrevious(){
    	setCon.previous();
    	makeDisClass( (List<PlantApply__c>)setCon.getRecords() );
    }
    
    /*
    * 次のページへ
    */
    public void getNext(){
    	setCon.next();
    	makeDisClass( (List<PlantApply__c>)setCon.getRecords() );
    }
    
     /*
    * 最後のページへ
    */
    public void getlast(){
    	setCon.last();
    	makeDisClass( (List<PlantApply__c>)setCon.getRecords() );
    }

  /*
    *
    * 画面表示用リストを作成
    *
    */
    private void makeDisClass( List<PlantApply__c> results ){
		// 表示用リスト
        this.disList = new List<DisClass>();
        // 選択されたのレコードID
        this.selectedId = null;
        
    	// 表示用リストを作成する
    	for( PlantApply__c pa : results ){
    		this.disList.add(new DisClass(pa,false));
    	}
    	// 該当画面番号
    	currentPageNo = setCon.getPageNumber();
    	resultSize = setCon.getResultSize();
    	if(currentPageNo*PAGESIZE > resultSize){
    		showMaxSize = resultSize;
    	}else{
    		showMaxSize = currentPageNo*PAGESIZE+1;
    	}    	
    }

ページ番号表示

public List<Integer> getPageNo(){
    	Integer disNo = 4;
    	List<Integer> noList = new List<Integer>();
    	// 総頁数
    	Integer totalPageNo = (Integer)((Decimal)resultSize/PAGESIZE).round(System.RoundingMode.UP);
    	// Loop回数
    	Integer roundPageNo = (Integer)((Decimal)currentPageNo/disNo).round(System.RoundingMode.UP);
    	// 開始頁数
    	Integer pageStartNo = ( roundPageNo == 1 ? 1 : roundPageNo * disNo - disNo + 1 );
    	// 終了頁数
    	Integer pageEndNo = ( roundPageNo*disNo > totalPageNo ? totalPageNo : roundPageNo*disNo );
    	
    	for( Integer i = pageStartNo; i <= pageEndNo; i++  ){
    		noList.add(i);
    	}
    	return noList;
    }


下面的方法:# 新增方法:将JSON格式的数据字典保存为Excel文件 def save_json_data_to_excel(json_data: dict, output_path: str) -> Path: “”" 将JSON格式的数据字典保存为Excel文件 参数: json_data (dict): 包含columns和data的字典 output_path (str): 完整的输出文件路径(包括文件名) 返回: Path: 生成的Excel文件路径 数据结构示例: json_data = { "columns": ["NO", "変更後:制御仕様書No", "用户新增列1", "用户新增列2"], "data": [ [1, "CS-001", "测试数据1", "补充信息1"], [2, "CS-002", "测试数据2", "补充信息2"], [3, "CS-003", "测试数据3", "补充信息3"] ] } """ try: # 确保输出目录存在 output_dir = Path(output_path).parent output_dir.mkdir(parents=True, exist_ok=True) # 验证JSON数据结构 required_keys = ['columns', 'data'] if not all(key in json_data for key in required_keys): missing_keys = [key for key in required_keys if key not in json_data] raise ValueError(f"JSON数据缺少必要键: {missing_keys}") # 验证数据完整性 if len(json_data['data']) > 0: expected_cols = len(json_data['columns']) for i, row in enumerate(json_data['data']): if len(row) != expected_cols: raise ValueError( f"第 {i + 1} 行数据列数不匹配 (应为 {expected_cols}, 实际 {len(row)})\n" f"列名: {json_data['columns']}\n" f"行数据: {row}" ) # 创建DataFrame df = pd.DataFrame(json_data['data'], columns=json_data['columns']) # 添加生成时间戳作为新列 df['生成时间'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 保存为Excel文件 excel_path = Path(output_path) df.to_excel(excel_path, index=False, engine='openpyxl') print(f"✅ 成功导出Excel文件: {excel_path}") print(f"📊 数据统计: {len(df)} 行, {len(df.columns)} 列") return excel_path except Exception as e: print(f"❌ 导出失败: {str(e)}") # 记录详细错误信息 import traceback traceback.print_exc() raise 前端传过来的数据: [ { “number”: “11”, “flag”: “edit”, “シート名/ページ”: “xxx”, // 修的字段 “変更後”: “yyy” // 修的字段 }, { “number”: “22”, “flag”: “add”, “シート名/ページ”: “xxx”, // 修的字段 “変更後”: “yyy” // 修的字段 } ] 在scl_update_path上进行修特定单元格,number号1对应第四行,第三行是表头,“number”: “22”, “flag”: “add”, “シート名/ページ”: “xxx”, // 修的字段 “変更後”: “yyy” // 修的字段 flag后面都是表头,对应修第几列的单元格 现在不是重新写入了,是解析json数据,只修特定单元格内容
10-22
====================================================================== ERROR: test_empty_json_data (__main__.TestSaveJsonToExcel) 测试空JSON数据 ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 607, in test_empty_json_data result_path = save_json_data_to_excel(json_data, excel_path) File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 382, in save_json_data_to_excel data_dict = json.loads(json_data) File "C:\Users\kotei\AppData\Local\Programs\Python\Python310\Lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not list ====================================================================== ERROR: test_invalid_row_number (__main__.TestSaveJsonToExcel) 测试无效行号处理 ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 566, in test_invalid_row_number result_path = save_json_data_to_excel(json_data, excel_path) File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 382, in save_json_data_to_excel data_dict = json.loads(json_data) File "C:\Users\kotei\AppData\Local\Programs\Python\Python310\Lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not list ====================================================================== ERROR: test_missing_column (__main__.TestSaveJsonToExcel) 测试缺少列名的情况 ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 587, in test_missing_column result_path = save_json_data_to_excel(json_data, excel_path) File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 382, in save_json_data_to_excel data_dict = json.loads(json_data) File "C:\Users\kotei\AppData\Local\Programs\Python\Python310\Lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not list ====================================================================== ERROR: test_non_existent_file (__main__.TestSaveJsonToExcel) 测试文件不存在的情况 ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 600, in test_non_existent_file save_json_data_to_excel(json_data, non_existent_path) File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 382, in save_json_data_to_excel data_dict = json.loads(json_data) File "C:\Users\kotei\AppData\Local\Programs\Python\Python310\Lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not list ====================================================================== ERROR: test_valid_modification (__main__.TestSaveJsonToExcel) 测试有效修 ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 541, in test_valid_modification result_path = save_json_data_to_excel(json_data, excel_path) File "D:\GitProjects\REQManagement\DDE\kotei_web_server\utils\test.py", line 382, in save_json_data_to_excel data_dict = json.loads(json_data) File "C:\Users\kotei\AppData\Local\Programs\Python\Python310\Lib\json\__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not list ---------------------------------------------------------------------- class TestSaveJsonToExcel(unittest.TestCase): @classmethod def setUpClass(cls): cls.test_dir = TemporaryDirectory() cls.base_path = Path(cls.test_dir.name) @classmethod def tearDownClass(cls): cls.test_dir.cleanup() def create_temp_excel(self, filename): """创建测试用的Excel文件""" file_path = self.base_path / filename # 创建示例Excel文件 df = pd.DataFrame({ "NO": [1, 2, 3], "変更後:制御仕様書No": ["CS-001", "CS-002", "CS-003"], "シート名/ページ": ["Page_A", "Page_B", "Page_C"], "変更後": ["内容A", "内容B", "内容C"] }) # 添加空行作为表头行(第3行) with pd.ExcelWriter(file_path, engine='openpyxl') as writer: df.to_excel(writer, index=False, startrow=2) # 从第3行开始写数据 print(f"📝 创建测试文件: {file_path}") return str(file_path) def test_valid_modification(self): """测试有效修""" excel_path = self.create_temp_excel("test_valid.xlsx") # 测试数据:修第1行(number=1)和第3行(number=3) json_data = [ { "number": "1", "flag": "edit", "シート名/ページ": "更新页面", "変更後": "重要变更" }, { "number": "3", "flag": "add", "シート名/ページ": "最终页面", "変更後": "最终内容" } ] # 执行修 result_path = save_json_data_to_excel(json_data, excel_path) self.assertEqual(result_path, Path(excel_path)) # 验证修结果 wb = load_workbook(excel_path) sheet = wb.active # 验证第4行修 (number=1 → 第4行) self.assertEqual(sheet.cell(row=4, column=3).value, "更新页面") # シート名/ページ self.assertEqual(sheet.cell(row=4, column=4).value, "重要变更") # 変更後 # 验证第6行修 (number=3 → 第6行) self.assertEqual(sheet.cell(row=6, column=3).value, "最终页面") self.assertEqual(sheet.cell(row=6, column=4).value, "最终内容") def test_invalid_row_number(self): """测试无效行号处理""" excel_path = self.create_temp_excel("test_invalid_row.xlsx") json_data = [ {"number": "100", "flag": "edit", "シート名/ページ": "无效行"}, # 超出范围 {"number": "abc", "flag": "edit", "変更後": "无效数字"}, # 非数字 {"number": "-1", "flag": "edit", "変更後": "负数"} # 无效数字 ] result_path = save_json_data_to_excel(json_data, excel_path) wb = load_workbook(excel_path) sheet = wb.active # 验证没有修 self.assertEqual(sheet.cell(row=4, column=3).value, "Page_A") self.assertEqual(sheet.cell(row=5, column=3).value, "Page_B") self.assertEqual(sheet.cell(row=6, column=3).value, "Page_C") def test_missing_column(self): """测试缺少列名的情况""" excel_path = self.create_temp_excel("test_missing_column.xlsx") json_data = [ { "number": "1", "flag": "edit", "不存在列": "测试值" # 不存在的列 } ] result_path = save_json_data_to_excel(json_data, excel_path) # 验证工作表未被修 wb = load_workbook(excel_path) sheet = wb.active self.assertEqual(sheet.cell(row=4, column=3).value, "Page_A") def test_non_existent_file(self): """测试文件不存在的情况""" json_data = [{"number": "1", "flag": "edit", "変更後": "测试"}] non_existent_path = str(self.base_path / "non_existent.xlsx") with self.assertRaises(FileNotFoundError): save_json_data_to_excel(json_data, non_existent_path) def test_empty_json_data(self): """测试空JSON数据""" excel_path = self.create_temp_excel("test_empty.xlsx") json_data = [] result_path = save_json_data_to_excel(json_data, excel_path) # 验证文件未被修 wb = load_workbook(excel_path) sheet = wb.active self.assertEqual(sheet.cell(row=4, column=3).value, "Page_A") def save_json_data_to_excel(json_data: list, output_path: str) -> Path: """ 根据JSON数据修Excel文件中的特定单元格 参数: json_data (list): 包含修信息的字典列表(已解析的JSON对象) output_path (str): 完整的输出文件路径(包括文件名) 返回: Path: 生成的Excel文件路径 """ try: # 确保输出目录存在 output_dir = Path(output_path).parent output_dir.mkdir(parents=True, exist_ok=True) # 验证JSON数据结构 if not isinstance(json_data, list): raise TypeError("json_data应为字典列表") # 检查文件是否存在 file_path = Path(output_path) if not file_path.exists(): raise FileNotFoundError(f"目标Excel文件不存在: {file_path}") # 加载Excel工作簿 wb = load_workbook(filename=output_path) sheet = wb.active # 验证表头行(第3行) HEADER_ROW = 3 if sheet.max_column < 1 or sheet.max_row < HEADER_ROW: raise ValueError("Excel文件缺少表头行") # 构建列名映射(表头名称 -> 列字母) header_map = {} for col_idx in range(1, sheet.max_column + 1): cell_value = sheet.cell(row=HEADER_ROW, column=col_idx).value if cell_value: header_map[cell_value] = col_idx # 处理每条修记录 for record in json_data: # 验证记录格式 if not isinstance(record, dict): print(f"⚠️ 跳过无效记录类型: {type(record)}") continue # 获取行号(number对应第4行开始) try: data_row = int(record.get("number", 0)) + 3 # number=1 -> 第4行 if data_row <= HEADER_ROW or data_row > sheet.max_row: print(f"⚠️ 跳过无效行号: {record.get('number')}") continue except (TypeError, ValueError): print(f"⚠️ 无效的number格式: {record.get('number')}") continue # 更新单元格 for field, value in record.items(): # 跳过系统字段 if field in ["number", "flag"]: continue # 查找对应列 if field not in header_map: print(f"⚠️ 表头中未找到列: {field}") continue col_idx = header_map[field] sheet.cell(row=data_row, column=col_idx, value=value) print(f"🖊️ 更新单元格 [{field}-行{data_row}]: {value}") # 保存修后的Excel wb.save(output_path) print(f"✅ 成功更新Excel文件: {file_path}") return file_path except Exception as e: print(f"❌ 修失败: {str(e)}") import traceback traceback.print_exc() raise
10-22
【无人机】基于进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与进中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值