初试Rust
先上效果图

背景
昨天写了一个小脚本,用Python帮我自动汇总业务人员的活动报告,节省了不少的时间。
俗话说,独乐乐 不如众乐乐,何不将其制作成可执行文件,分发给嘉智联的小伙伴们使用呢?
经常把大象放进冰箱里的帅哥都知道,将业务逻辑用Python验证后,用更高效语言重写的方法一般如下:
- 打开AI助手
- py文件和业务表格喂食给AI
- 提出改写需求(顺便加个UI)
- 测试并完成
改写后的Rust脚本
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use anyhow::{Context, Result};
use calamine::{open_workbook, Reader, Xlsx};
use chrono::NaiveDateTime;
use eframe::egui;
use rust_xlsxwriter::{
Format, FormatAlign, FormatBorder, Workbook,
};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use walkdir::WalkDir;
// 线程安全的共享状态
struct SharedState {
log: Vec<String>,
status: String,
processing: bool,
}
#[derive(Clone)]
struct ExcelSummaryApp {
input_dir: String,
output_path: String,
shared_state: Arc<Mutex<SharedState>>,
}
impl Default for ExcelSummaryApp {
fn default() -> Self {
Self {
input_dir: String::new(),
output_path: String::new(),
shared_state: Arc::new(Mutex::new(SharedState {
log: Vec::new(),
status: String::new(),
processing: false,
})),
}
}
}
#[derive(Debug)]
struct ActivityInfo {
topic: String,
jzl_person: String,
location: String,
time: String,
organizer: String,
contact_person: String,
contact_number: String,
agenda: String,
summary: String,
source_file: String,
}
impl eframe::App for ExcelSummaryApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
// 锁定共享状态以读取
let state = self.shared_state.lock().unwrap();
let status = state.status.clone();
let log = state.log.clone();
let processing = state.processing;
drop(state); // 提前释放锁
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("嘉智联活动信息汇总工具");
ui.separator();
// 输入文件夹选择
ui.horizontal(|ui| {
ui.label("输入文件夹:");
ui.text_edit_singleline(&mut self.input_dir);
if ui.button("浏览...").clicked() {
if let Some(path) = rfd::FileDialog::new().pick_folder() {
self.input_dir = path.to_string_lossy().to_string();
}
}
});
// 输出文件选择
ui.horizontal(|ui| {
ui.label("输出文件:");
ui.text_edit_singleline(&mut self.output_path);
if ui.button("浏览...").clicked() {
if let Some(path) = rfd::FileDialog::new()
.add_filter("Excel文件", &["xlsx"])
.save_file()
{
let path_str = path.to_string_lossy().to_string();
self.output_path = if path_str.ends_with(".xlsx") {
path_str
} else {
format!("{}.xlsx", path_str)
};
}
}
});
ui.separator();
// 处理按钮
ui.horizontal(|ui| {
let button_enabled = !processing
&& !self.input_dir.is_empty()
&& !self.output_path.is_empty()
&& Path::new(&self.input_dir).exists();
let button = ui.add_enabled(button_enabled, egui::Button::new("开始汇总").min_size(egui::vec2(120.0, 30.0)));
if button.clicked() {
// 更新状态为处理中
let mut state = self.shared_state.lock().unwrap();
state.processing = true;
state.status = "正在处理...".to_string();
state.log.clear();
drop(state); // 释放锁
// 克隆必要的数据以传递给线程
let input_dir = self.input_dir.clone();
let output_path = self.output_path.clone();
let shared_state = Arc::clone(&self.shared_state);
// 在新线程中处理,避免UI卡顿
std::thread::spawn(move || {
let mut log = Vec::new();
let result = process_excel_files(&input_dir, &output_path, &mut log);
// 更新状态
let mut state = shared_state.lock().unwrap();
state.status = match result {
Ok(_) => "处理完成!".to_string(),
Err(e) => format!("处理失败: {}", e),
};
state.log = log;
state.processing = false;
});
}
});
// 状态显示
ui.label(&status);
// 日志显示
ui.separator();
ui.label("处理日志:");
egui::ScrollArea::vertical().show(ui, |ui| {
for line in &log {
ui.label(line);
}
});
});
// 每帧请求重绘以更新状态
ctx.request_repaint();
}
}
fn process_excel_files(input_dir: &str, output_path: &str, log: &mut Vec<String>) -> Result<()> {
log.push(format!("开始处理文件夹: {}", input_dir));
// 查找所有Excel文件
let excel_files: Vec<PathBuf> = WalkDir::new(input_dir)
.into_iter()
.filter_map(|e| e.ok())
.filter(|e| {
e.file_type().is_file() &&
matches!(e.path().extension().and_then(|s| s.to_str()),
Some("xlsx") | Some("xls")) &&
!e.path().file_name().and_then(|s| s.to_str()).map_or(false, |n| n.contains("汇总"))
})
.map(|e| e.path().to_path_buf())
.collect();
log.push(format!("找到 {} 个Excel文件", excel_files.len()));
if excel_files.is_empty() {
return Ok(());
}
// 提取每个文件的信息
let mut activities = Vec::new();
for path in &excel_files {
log.push(format!("处理文件: {}", path.to_string_lossy()));
match extract_activity_info(path) {
Ok(info) => activities.push(info),
Err(e) => log.push(format!("处理文件 {} 时出错: {}", path.to_string_lossy(), e)),
}
}
// 生成输出Excel
generate_output_excel(&activities, output_path, log)?;
log.push(format!("汇总完成,结果保存至: {}", output_path));
Ok(())
}
fn extract_activity_info(path: &Path) -> Result<ActivityInfo> {
let mut workbook: Xlsx<_> = open_workbook(path)
.with_context(|| format!("无法打开文件: {}", path.to_string_lossy()))?;
let sheet_names = workbook.sheet_names().to_vec();
if sheet_names.is_empty() {
return Err(anyhow::anyhow!("文件中没有工作表"));
}
let first_sheet = &sheet_names[0];
let range = workbook.worksheet_range(first_sheet)
.with_context(|| format!("无法读取工作表: {}", first_sheet))?;
let max_row = range.height() as usize;
// 辅助函数:安全获取单元格值,使用具体的Xlsx数据类型
fn get_cell_value(range: &calamine::Range<calamine::Data>, row: usize, col: usize) -> String {
if row < range.height() as usize && col < range.width() as usize {
match range.get((row, col)).unwrap_or(&calamine::Data::Empty) {
calamine::Data::String(s) => s.clone(),
calamine::Data::Float(f) => f.to_string(),
calamine::Data::Int(i) => i.to_string(),
calamine::Data::Bool(b) => b.to_string(),
calamine::Data::DateTime(d) => d.to_string(),
calamine::Data::Empty => String::new(),
calamine::Data::Error(_) => String::new(),
calamine::Data::DateTimeIso(s) => s.clone(),
calamine::Data::DurationIso(s) => s.clone(),
}
} else {
String::new()
}
}
// 查找"嘉智联渠道市场推广活动报告"所在列
let topic_col = (0..range.width() as usize)
.find(|&col| get_cell_value(&range, 0, col).contains("嘉智联渠道市场推广活动报告"))
.ok_or_else(|| anyhow::anyhow!("未找到标题列"))?;
// 查找各Unnamed列(根据实际数据分布估算)
let unnamed_2_col = topic_col + 2;
let unnamed_5_col = topic_col + 5;
let unnamed_7_col = topic_col + 7;
let unnamed_8_col = topic_col + 8;
// 提取所需内容,增加索引检查(与Python脚本保持一致)
let activity_topic = if 2 < max_row {
get_cell_value(&range, 2, topic_col)
} else {
String::new()
};
let jzl_person_in_charge = if 2 < max_row {
get_cell_value(&range, 2, unnamed_8_col)
} else {
String::new()
};
let mut activity_location = if 5 < max_row {
get_cell_value(&range, 5, topic_col)
} else {
String::new()
};
// 移除活动地点中的下划线
activity_location = activity_location.replace('_', "");
let activity_time = if 5 < max_row {
get_cell_value(&range, 5, unnamed_5_col)
} else {
String::new()
};
let organizer = if 8 < max_row {
get_cell_value(&range, 8, topic_col)
} else {
String::new()
};
let contact_person = if 8 < max_row {
get_cell_value(&range, 8, unnamed_7_col)
} else {
String::new()
};
// 根据测试结果修正:联系电话在第8行,Unnamed:7列
let contact_number = if 9 < max_row {
get_cell_value(&range, 9, unnamed_7_col)
} else {
String::new()
};
// 活动议程部分
let mut activity_agenda = String::new();
let agenda_start = 12;
let agenda_end = 19;
if agenda_start < max_row {
let actual_end = std::cmp::min(agenda_end, max_row - 1);
let mut agenda_items = Vec::new();
for row in agenda_start..=actual_end {
let time = get_cell_value(&range, row, topic_col);
let agenda = get_cell_value(&range, row, unnamed_2_col);
let person = get_cell_value(&range, row, unnamed_7_col);
// 处理时间格式,将Excel数字格式转换为时间格式
let formatted_time = if let Ok(numeric_time) = time.parse::<f64>() {
// 如果是数字格式的时间,转换为小时:分钟格式
let hours = (numeric_time * 24.0).floor() as u32;
let minutes = ((numeric_time * 24.0 * 60.0) % 60.0).round() as u32;
format!("{:02}:{:02}", hours % 24, minutes)
} else {
time.clone()
};
if !formatted_time.is_empty() || !agenda.is_empty() {
if !person.is_empty() {
agenda_items.push(format!("{} - {}({})", formatted_time, agenda, person));
} else {
agenda_items.push(format!("{} - {}", formatted_time, agenda));
}
}
}
activity_agenda = agenda_items.join(";");
}
// 活动小结 - 从36行到43行(index=35到42)和A列到J列(index=0到9)提取内容
let mut activity_summary = String::new();
let summary_start = 35;
let summary_end = 42;
let col_start = 0;
let col_end = 9;
if summary_start < max_row {
let actual_summary_end = std::cmp::min(summary_end, max_row - 1);
let actual_col_end = std::cmp::min(col_end, range.width() as usize - 1);
let mut summary_cells = Vec::new();
for row_idx in summary_start..=actual_summary_end {
for col_idx in col_start..=actual_col_end {
let cell_value = get_cell_value(&range, row_idx, col_idx);
if !cell_value.trim().is_empty() {
summary_cells.push(cell_value.trim().to_string());
}
}
}
activity_summary = summary_cells.join(" ");
}
Ok(ActivityInfo {
topic: activity_topic.trim().to_string(),
jzl_person: jzl_person_in_charge.trim().to_string(),
location: activity_location.trim().to_string(),
time: activity_time.trim().to_string(),
organizer: organizer.trim().to_string(),
contact_person: contact_person.trim().to_string(),
contact_number: contact_number.trim().to_string(),
agenda: activity_agenda,
summary: activity_summary,
source_file: path.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string(),
})
}
fn generate_output_excel(activities: &[ActivityInfo], output_path: &str, _log: &mut Vec<String>) -> Result<()> {
let mut workbook = Workbook::new();
// 创建格式 - 使用构建器模式避免所有权问题
let header_format = Format::new()
.set_bold()
.set_border(FormatBorder::Thin)
.set_align(FormatAlign::Center);
let default_format = Format::new()
.set_border(FormatBorder::Thin)
.set_text_wrap();
let date_format = Format::new()
.set_border(FormatBorder::Thin)
.set_text_wrap()
.set_align(FormatAlign::Center)
.set_num_format("yyyy-mm-dd hh:mm");
let phone_format = Format::new()
.set_border(FormatBorder::Thin)
.set_text_wrap()
.set_num_format("@");
let agenda_format = Format::new()
.set_border(FormatBorder::Thin)
.set_text_wrap();
// 添加工作表
let worksheet = workbook.add_worksheet();
// 设置列宽
worksheet.set_column_width(0, 30.0)?; // 活动主题
worksheet.set_column_width(1, 12.0)?; // 嘉智联担当
worksheet.set_column_width(2, 25.0)?; // 活动地点
worksheet.set_column_width(3, 20.0)?; // 活动时间
worksheet.set_column_width(4, 15.0)?; // 主办单位
worksheet.set_column_width(5, 12.0)?; // 联系人
worksheet.set_column_width(6, 15.0)?; // 联系电话
worksheet.set_column_width(7, 40.0)?; // 活动议程
worksheet.set_column_width(8, 50.0)?; // 活动小结
worksheet.set_column_width(9, 20.0)?; // 来源文件
// 写入表头
let headers = [
"活动主题", "嘉智联担当", "活动地点", "活动时间", "主办单位",
"联系人", "联系电话", "活动议程", "活动小结", "原始报告"
];
for (col, header) in headers.iter().enumerate() {
worksheet.write_with_format(0, col as u16, *header, &header_format)?;
}
// 写入数据
for (row_idx, activity) in activities.iter().enumerate() {
let row = (row_idx + 1) as u32;
worksheet.write_with_format(row, 0, &activity.topic, &default_format)?;
worksheet.write_with_format(row, 1, &activity.jzl_person, &default_format)?;
worksheet.write_with_format(row, 2, &activity.location, &default_format)?;
// 尝试解析日期
if let Ok(date) = NaiveDateTime::parse_from_str(&activity.time, "%Y年%m月%d日 %H:%M") {
worksheet.write_with_format(row, 3, date.to_string(), &date_format)?;
} else {
worksheet.write_with_format(row, 3, &activity.time, &date_format)?;
}
worksheet.write_with_format(row, 4, &activity.organizer, &default_format)?;
worksheet.write_with_format(row, 5, &activity.contact_person, &default_format)?;
worksheet.write_with_format(row, 6, &activity.contact_number, &phone_format)?;
// 使用专用格式写入活动议程列,并将分号替换为换行符以实现真正的自动换行
let formatted_agenda = activity.agenda.replace(";", "\n");
worksheet.write_with_format(row, 7, &formatted_agenda, &agenda_format)?;
worksheet.write_with_format(row, 8, &activity.summary, &default_format)?;
worksheet.write_with_format(row, 9, &activity.source_file, &default_format)?;
}
// 保存文件
workbook.save(output_path).with_context(|| format!("无法保存文件: {}", output_path))?;
Ok(())
}
fn main() -> Result<()> {
let options = eframe::NativeOptions {
initial_window_size: Some(egui::vec2(800.0, 600.0)),
..Default::default()
};
let _ = eframe::run_native(
"嘉智联活动信息汇总工具",
options,
Box::new(|cc| {
// 设置中文字体支持 - 动态检测并使用系统字体
setup_fonts(cc);
Box::new(ExcelSummaryApp::default())
}),
);
Ok(())
}
// 设置字体的函数
fn setup_fonts(cc: &eframe::CreationContext<'_>) {
// 获取系统字体
let mut fonts = egui::FontDefinitions::default();
// 在Windows系统上尝试使用系统默认中文字体
if cfg!(target_os = "windows") {
// Windows系统常见的中文字体路径
let system_fonts = [
"C:\\Windows\\Fonts\\msyh.ttc", // 微软雅黑
"C:\\Windows\\Fonts\\msyh.ttf", // 微软雅黑
"C:\\Windows\\Fonts\\simhei.ttf", // 黑体
"C:\\Windows\\Fonts\\simsun.ttc", // 宋体
"C:\\Windows\\Fonts\\simkai.ttf", // 楷体
];
// 检查系统字体文件是否存在,如果存在则使用
for font_path in &system_fonts {
if std::path::Path::new(font_path).exists() {
match std::fs::read(font_path) {
Ok(font_data) => {
fonts.font_data.insert(
"SystemChineseFont".to_owned(),
egui::FontData::from_owned(font_data),
);
fonts.families.get_mut(&egui::FontFamily::Proportional).unwrap()
.insert(0, "SystemChineseFont".to_owned());
fonts.families.get_mut(&egui::FontFamily::Monospace).unwrap()
.insert(0, "SystemChineseFont".to_owned());
// 找到第一个可用字体就退出循环
break;
}
Err(_) => continue,
}
}
}
}
cc.egui_ctx.set_fonts(fonts);
}
最终生成exe文件,文件大小仅仅4335K,以及超快的运行速度,这是Python无法比拟的优势。

