1016. Phone Bills (25)

本文介绍了一个基于时间的电话账单事件模拟程序,该程序通过记录电话的接通和挂断时间来计算通话费用及持续时间。利用C++实现,文章详细展示了如何处理电话账单数据、过滤无效记录并计算费用。

参考自:

考察以时间为核心的电话账单事件模拟以及统计

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




struct Call
{
	string name;
	int month;
	int date;
	int hour;
	int minute;
	int total;
	string status;
};

int charge[24];
vector<Call> all_calls;
vector<Call> format_calls;

bool compare(Call a,Call b)
{
	if(a.name < b.name)
		return 1;
	else if(a.name == b.name && a.total < b.total)
		return 1;
	else
		return 0;
}

void show(Call c)
{
	cout<<c.name<<" ";
	cout<<c.month<<":"<<c.date<<":"<<c.hour<<":"<<c.minute<<" ";
	cout<<c.status<<endl;
}

//calculate money from the begin of month to the time given
int chargeByTime(int time)
{
	int hours = time/60;
	int minutes = time%60;
	int money = 0;
	int i;
	for(i = 0;i<hours;i++)
		money += charge[i%24]*60;
	money += charge[i%24]*minutes;
	return money;
}

double calCost(Call s,Call t)
{
	return (double)(chargeByTime(t.total)-chargeByTime(s.total))/100;
}

int calLast(Call s,Call t)
{
	return (t.date-s.date)*24*60+(t.hour-s.hour)*60+(t.minute-s.minute);
}



int main()
{
	for(int i = 0;i<24;i++)
		cin>>charge[i];
	int N;
	cin>>N;
	while(N--)
	{
		Call c;
		cin>>c.name;
		cin>>c.month;
		getchar();
		cin>>c.date;
		getchar();
		cin>>c.hour;
		getchar();
		cin>>c.minute;
		c.total = c.minute + 60*c.hour + 24*60*c.date;
		cin>>c.status;
		all_calls.push_back(c);
	}
	sort(all_calls.begin(),all_calls.end(),compare);

	//filter delete those bad record
	bool haveonline = false;
	string curname;
	for(int i=0;i<all_calls.size();i++)
	{
		if(haveonline == false && all_calls[i].status =="on-line" )
		{
			format_calls.push_back(all_calls[i]);
			haveonline = true;
			curname = all_calls[i].name;
		}
		else if(haveonline == true && all_calls[i].status =="on-line")
		{
			format_calls.pop_back();
			format_calls.push_back(all_calls[i]);
			haveonline = true;
			curname = all_calls[i].name;
		}
		else if(haveonline == true && all_calls[i].status =="off-line"&&all_calls[i].name ==curname)
		{
			format_calls.push_back(all_calls[i]);
			haveonline = false;
		}
	}
	//the last must be offline
	if((*(format_calls.end()-1)).status == "on-line")
		format_calls.pop_back();

	//output
	double totalcost = 0;
	curname = "";
	for(int i=0;i<format_calls.size();i+=2)
	{

		if(format_calls[i].name != curname)
		{
			if(curname!="")
			{
				printf("Total amount: $%.2f\n",totalcost);
				totalcost = 0;
				printf("%s %02d\n",format_calls[i].name.c_str(),format_calls[i].month);
			}
			else
			{
				printf("%s %02d\n",format_calls[i].name.c_str(),format_calls[i].month);
			}
			curname = format_calls[i].name;
		}
		printf("%02d:%02d:%02d",format_calls[i].date,format_calls[i].hour,format_calls[i].minute);
		printf(" ");
		printf("%02d:%02d:%02d",format_calls[i+1].date,format_calls[i+1].hour,format_calls[i+1].minute);
		printf(" ");
		printf("%d",calLast(format_calls[i],format_calls[i+1]));
		printf(" ");
		printf("$%.2f\n",calCost(format_calls[i],format_calls[i+1]));
		totalcost+=calCost(format_calls[i],format_calls[i+1]);
	}
	printf("Total amount: $%.2f\n",totalcost);
	
	
}


 

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值