1016. Phone Bills (25)

本文介绍了一个基于时间分段费率的电话计费系统的实现方法。系统通过记录用户的通话起止时间和日期来计算费用,并能够处理同一用户多次通话的情况。文章详细展示了输入输出规格及样例,还提供了一种按姓名和时间排序的处理策略。

A long-distance telephone company charges its customers by the following rules:

Making a long-distance call costs a certain amount per minute, depending on the time of day when the call is made. When a customer starts connecting a long-distance call, the time will be recorded, and so will be the time when the customer hangs up the phone. Every calendar month, a bill is sent to the customer for each minute called (at a rate determined by the time of day). Your job is to prepare the bills for each month, given a set of phone call records.

Input Specification:

Each input file contains one test case. Each case has two parts: the rate structure, and the phone call records.

The rate structure consists of a line with 24 non-negative integers denoting the toll (cents/minute) from 00:00 - 01:00, the toll from 01:00 - 02:00, and so on for each hour in the day.

The next line contains a positive number N (<= 1000), followed by N lines of records. Each phone call record consists of the name of the customer (string of up to 20 characters without space), the time and date (mm:dd:hh:mm), and the word "on-line" or "off-line".

For each test case, all dates will be within a single month. Each "on-line" record is paired with the chronologically next record for the same customer provided it is an "off-line" record. Any "on-line" records that are not paired with an "off-line" record are ignored, as are "off-line" records not paired with an "on-line" record. It is guaranteed that at least one call is well paired in the input. You may assume that no two records for the same customer have the same time. Times are recorded using a 24-hour clock.

Output Specification:

For each test case, you must print a phone bill for each customer.

Bills must be printed in alphabetical order of customers' names. For each customer, first print in a line the name of the customer and the month of the bill in the format shown by the sample. Then for each time period of a call, print in one line the beginning and ending time and date (dd:hh:mm), the lasting time (in minute) and the charge of the call. The calls must be listed in chronological order. Finally, print the total charge for the month in the format shown by the sample.

Sample Input:
10 10 10 10 10 10 20 20 20 15 15 15 15 15 15 15 20 30 20 15 15 10 10 10
10
CYLL 01:01:06:01 on-line
CYLL 01:28:16:05 off-line
CYJJ 01:01:07:00 off-line
CYLL 01:01:08:03 off-line
CYJJ 01:01:05:59 on-line
aaa 01:01:01:03 on-line
aaa 01:02:00:01 on-line
CYLL 01:28:15:41 on-line
aaa 01:05:02:24 on-line
aaa 01:04:23:59 off-line
Sample Output:
CYJJ 01
01:05:59 01:07:00 61 $12.10
Total amount: $12.10
CYLL 01
01:06:01 01:08:03 122 $24.40
28:15:41 28:16:05 24 $3.85
Total amount: $28.25
aaa 01
02:00:01 04:23:59 4318 $638.80
Total amount: $638.80

借鉴了一下别人的思路,大概是按名称再按时间排序,再将匹配的信息插入vector 同一个人遇到online则判断前一个是不是offline,如果是online则弹出前一个后再插入是offline则直接插入, 遇到offline则判断前一个是不是online,是online直接插入,不是则不操作;

测试点1有一条是最后一个人为空,有一条是其中有个人为空

#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <iterator>
#include <algorithm>
#include <iomanip>
using namespace std;

struct info{
	string name;
	string time;
	string status;
};
const string on = "on-line";
const string off = "off-line";

bool cmp(const info &a, const info &b)
{
	if(a.name < b.name)
		return true;
	else if(a.name==b.name && a.time<b.time)
		return true;
	return false;
}
vector<info> record;
vector<info> person;
int toll[24];


void solve(vector<info> p);
double amount(string on, string off);
int main()
{
	int n;
	info temp;
	for(int i=0; i<24; i++)
		cin >> toll[i];
	cin >> n;
	cin.get();
	for(int i=0; i<n; i++)
    {
        cin >> temp.name >> temp.time >> temp.status;
        record.push_back(temp);
    }
	sort(record.begin(), record.end(), cmp);//按名字顺序如果名字相同则按时间顺序排
	for(int i=0; i<n; i++)
	{
		if(i==0 || (i!=0 && record[i].name==record[i-1].name))//当前面的数据为同一个人时
		{
			if(person.empty())
			{
				if(record[i].status == on)
					person.push_back(record[i]);
			}
			else{
				if(record[i].status == on)//如果即将插入数据为online则看尾部数据是online就弹出尾部数据,插入该数据
				{
					if(person.back().status == on)
					{
						person.pop_back();
						person.push_back(record[i]);
					}
					else{//为offline则匹配直接插入
						person.push_back(record[i]);
					}
				}
				else{//插入数据为offline则判断尾部是online则插入不是什么都不做
					if(person.back().status == on)
					{
						person.push_back(record[i]);
					}
				}
			}
		}
		else {//当名字更换时 即前一个名字和当前名字不同时
            if(!person.empty())//如果前面统计非空需要判断尾部是否是online
			{
			    if(person.back().status == on)
                    person.pop_back();
			}
            if(!person.empty())//弹出尾部后依旧非空则计算详细
                solve(person);
			person.clear();
            if(record[i].status == on)//该数据为online可插入
                person.push_back(record[i]);
		}
	}
	if(!person.empty())//最后一个人因为不会进去上面的else所以单独处理
    {
        if(person.back().status == on)
            person.pop_back();
        if(!person.empty())
            solve(person);
    }
	return 0;
}

void solve(vector<info> p)
{
    double totalamount = 0;
	string online;
	string offline;
	vector<info>::size_type i;
	cout << p[0].name << " " << p[0].time[0] << p[0].time[1] << endl;
	for(i=0; i<p.size(); i+=2)
	{
	    online = p[i].time.substr(3);//取天:时:分
	    offline = p[i+1].time.substr(3);
	    totalamount += amount(online, offline);
	}
	cout << fixed << setprecision(2) << "Total amount: $" << totalamount << endl;
}

double amount(string on, string off)
{
    double total = 0;
	int ondd, onhh, onmm, offdd, offhh, offmm;
	int minute = 0;
	ondd = (on[0]-'0')*10+(on[1]-'0');//分离出开始和结束的天时分并计算
	onhh = (on[3]-'0')*10+(on[4]-'0');
	onmm = (on[6]-'0')*10+(on[7]-'0');
	offdd = (off[0]-'0')*10+(off[1]-'0');
	offhh = (off[3]-'0')*10+(off[4]-'0');
	offmm = (off[6]-'0')*10+(off[7]-'0');
	while(ondd!=offdd || onhh!=offhh || onmm!=offmm)
    {
        total += toll[onhh];
        minute++;
        onmm++;
        if(onmm >= 60)
        {
            onmm = 0;
            onhh++;
            if(onhh >= 24)
            {
                onhh = 0;
                ondd++;
            }
        }
    }
	cout << fixed << setprecision(2) << on << " " << off << " " << minute << " $" << total/100 << endl;
	return total/100;
}


const handleExport = async () => { try { loading.value = true; // 格式化日期参数 const params = { billType: searchForm.billType, paymentStatus: searchForm.paymentStatus, accountId: searchForm.accountId, startDate: searchForm.dateRange?.[0] ? dayjs(searchForm.dateRange[0]).format("YYYY-MM-DD") : undefined, endDate: searchForm.dateRange?.[1] ? dayjs(searchForm.dateRange[1]).format("YYYY-MM-DD") : undefined, }; console.log("导出参数:", params); const response = await exportBill(params); console.log("响应数据:", response); // 处理Blob数据 const blob = new Blob([response.data], { type: response.headers["content-type"] || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); // 创建下载链接 const url = window.URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.setAttribute( "download", `账单_${new Date().toISOString().slice(0, 10)}.xlsx` ); document.body.appendChild(link); link.click(); // 清理 setTimeout(() => { document.body.removeChild(link); window.URL.revokeObjectURL(url); }, 100); ElMessage.success("导出成功"); } catch (error) { console.error("导出错误详情:", error); // 处理后端返回的JSON错误信息 if ( error.response && error.response.data && error.response.data instanceof Blob ) { const reader = new FileReader(); reader.onload = () => { try { const errMsg = JSON.parse(reader.result).message; ElMessage.error(`导出失败: ${errMsg}`); } catch (e) { ElMessage.error("导出失败: 未知错误"); } }; reader.readAsText(error.response.data); } else { ElMessage.error(`导出失败: ${error.message || "未知错误"}`); } } finally { loading.value = false; } };@GetMapping("/exportBill") public void exportBill( @RequestParam(required = false) Integer billType, @RequestParam(required = false) Integer paymentStatus, @RequestParam(required = false) Long accountId, @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, HttpServletResponse response) throws IOException { log.info("导出参数: billType={}, paymentStatus={}, accountId={}, startDate={}, endDate={}", billType, paymentStatus, accountId, startDate, endDate); try { // 1. 构建查询参数 BillExportReqDTO exportDTO = new BillExportReqDTO(); exportDTO.setBillType(billType); exportDTO.setPaymentStatus(paymentStatus); exportDTO.setAccountId(accountId); // 日期转换处理 if (StringUtils.isNotBlank(startDate)) { exportDTO.setStartDate(Date.valueOf(startDate)); } if (StringUtils.isNotBlank(endDate)) { exportDTO.setEndDate(Date.valueOf(endDate)); } // 2. 设置响应头 String fileName = "账单_" + LocalDate.now() + ".xlsx"; response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8")); // 3. 导出Excel billService.exportBill(exportDTO, response.getOutputStream()); } catch (Exception e) { log.error("导出Excel失败", e); response.reset(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(String.valueOf(Result.error("导出失败: " + e.getMessage()))); } } @Override public void exportBill(BillExportReqDTO exportDTO, OutputStream outputStream) { // 1. 查询数据 List<bills> bills = billMapper.selectBillsForExport(exportDTO); if (CollectionUtils.isEmpty(bills)) { throw new RuntimeException("没有可导出的数据"); } // 2. 导出Excel try (ExcelWriter excelWriter = EasyExcel.write(outputStream) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽 .build()) { WriteSheet writeSheet = EasyExcel.writerSheet("账单数据") .head(BillExcelRespDTO.class) .registerWriteHandler(new HorizontalCellStyleStrategy( getHeaderStyle(), getContentStyle())) // 自定义样式 .build(); // 3. 数据转换并写入Excel excelWriter.write(convertToExcelVO(bills), writeSheet); excelWriter.finish(); // 确保写入完成 } } private List<BillExcelRespDTO> convertToExcelVO(List<bills> bills) { return bills.stream().map(bill -> { BillExcelRespDTO vo = new BillExcelRespDTO(); // 这里进行属性拷贝 BeanUtils.copyProperties(bill, vo); // 特殊字段处理 vo.setPaymentStatus(String.valueOf(bill.getPaymentStatus())); return vo; }).collect(Collectors.toList()); } // 内容单元格样式 private WriteCellStyle getContentStyle() { WriteCellStyle style = new WriteCellStyle(); // 1. 对齐方式 style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 水平居中 style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中 // 2. 边框设置 style.setBorderLeft(BorderStyle.THIN); // 左边框 style.setBorderRight(BorderStyle.THIN); // 右边框 style.setBorderTop(BorderStyle.THIN); // 上边框 style.setBorderBottom(BorderStyle.THIN); // 下边框 style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 边框颜色 style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); // 3. 背景色(默认白色,可不设置) style.setFillPatternType(FillPatternType.SOLID_FOREGROUND); style.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 4. 字体样式 WriteFont font = new WriteFont(); font.setFontName("宋体"); // 字体 font.setFontHeightInPoints((short) 11); // 字号 font.setColor(IndexedColors.BLACK.getIndex()); // 字体颜色 style.setWriteFont(font); // 5. 自动换行(根据需求) style.setWrapped(true); return style; } // 自定义表头样式 private WriteCellStyle getHeaderStyle() { WriteCellStyle style = new WriteCellStyle(); style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); style.setHorizontalAlignment(HorizontalAlignment.CENTER); // 其他样式设置... return style; }, <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.bankmanage.mapper.BillMapper"> <select id="selectBillsForExport" resultType="com.example.bankmanage.entity.bills"> SELECT * FROM bills <where> <if test="billType != null"> AND bill_type = #{billType} </if> <if test="paymentStatus != null"> AND payment_status = #{paymentStatus} </if> <if test="accountId != null"> AND account_id = #{accountId} </if> <if test="startDate != null"> AND due_date >= #{startDate} </if> <if test="endDate != null"> AND due_date <![CDATA[<=]]> #{endDate} </if> </where> ORDER BY due_date DESC </select> </mapper> package com.example.bankmanage.dto.resq; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.format.DateTimeFormat; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.sql.Date; @Data @NoArgsConstructor @AllArgsConstructor @Builder @SuppressWarnings("all") public class BillExcelRespDTO { @ExcelProperty("账单编号") private String billNo; @ExcelProperty("账户ID") private Long accountId; @ExcelProperty("账单类型") private String billType; @ExcelProperty("金额") private BigDecimal amount; @ExcelProperty("支付状态") private String paymentStatus; @ExcelProperty("创建时间") @DateTimeFormat("yyyy-MM-dd HH:mm:ss") private Date createTime; @ExcelProperty("支付时间") @DateTimeFormat("yyyy-MM-dd HH:mm:ss") private Date paymentTime; } 根据以上代码为什么我Excel导出指令不成功,请给我一个修正版
最新发布
06-06
### 修正后的Excel导出功能实现 #### 后端逻辑修正 在后端代码中,`SysUserController.java` 的 `exportExcelUser` 方法可能存在以下问题:文件生成失败、文件下载失败或请求参数不完整。以下是修正后的代码: ```java @PostMapping(value = "/exportExcelUser") public void exportExcelUser(@RequestBody PageRequest pageRequest, HttpServletResponse response) { try { // 确保传入的PageRequest对象包含所有必要参数 if (pageRequest == null || pageRequest.getConditions() == null) { throw new IllegalArgumentException("请求参数为空"); } // 调用服务层生成Excel文件 File file = sysUserService.createUserExcelFile(pageRequest); // 检查文件是否成功生成 if (file == null || !file.exists()) { throw new IOException("Excel文件生成失败"); } // 设置响应头,确保浏览器能够正确下载文件 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8")); // 下载文件 FileUtils.downloadFile(response, file, file.getName()); // 删除临时文件以节省服务器空间 if (!file.delete()) { logger.warn("临时文件删除失败:" + file.getAbsolutePath()); } } catch (Exception e) { // 捕获异常并返回错误信息 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setContentType("text/plain;charset=UTF-8"); try { response.getWriter().write("导出失败:" + e.getMessage()); } catch (IOException ex) { logger.error("导出失败时无法写入响应内容", ex); } throw new RuntimeException("Excel导出失败", e); } } ``` 上述代码增加了对 `PageRequest` 参数的校验[^1],并确保文件生成失败时抛出异常。同时,通过设置响应头和删除临时文件的方式优化了文件下载流程。 #### MyBatis查询修正 假设 `sysUserService.createUserExcelFile(PageRequest pageRequest)` 方法依赖于 MyBatis 查询用户数据。如果查询结果为空或映射错误,可能导致 Excel 文件生成失败。以下是修正后的 SQL 和 Mapper 示例: **Mapper XML 文件** ```xml <select id="selectUsersForExport" resultType="com.example.domain.User"> SELECT id, username, email, phone, created_at FROM users <where> <if test="conditions.username != null and conditions.username != ''"> AND username LIKE CONCAT('%', #{conditions.username}, '%') </if> <if test="conditions.email != null and conditions.email != ''"> AND email = #{conditions.email} </if> </where> </select> ``` **MyBatis Mapper 接口** ```java public interface SysUserMapper { List<User> selectUsersForExport(@Param("conditions") Map<String, Object> conditions); } ``` 确保 `ResultMap` 映射正确[^4],并且查询条件与 `PageRequest` 对象中的字段一致。 #### 前端调用修正 前端需要通过 Axios 或 Fetch API 调用后端接口,并处理文件下载。以下是修正后的 Vue.js 前端代码示例: ```javascript methods: { exportExcel() { const params = { conditions: { username: this.searchForm.username, email: this.searchForm.email } }; axios.post('/api/sysUser/exportExcelUser', params, { responseType: 'blob', // 确保响应类型为二进制流 headers: { 'Content-Type': 'application/json' } }).then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', '用户列表.xlsx'); // 设置下载文件名 document.body.appendChild(link); link.click(); }).catch(error => { console.error("导出失败:" + error.message); alert("导出失败,请检查日志!"); }); } } ``` 上述代码通过设置 `responseType: 'blob'` 来处理二进制文件流[^2],并动态创建下载链接完成文件保存。 --- ####
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值