rust初学记录-excel导出

佐手、 提交于 2021-01-18 14:03:29

尝试使用 rocket 导出excel文件 。

使用 toolchain 是  stable-x86_64-pc-windows-gnu 

Cargo.toml 

[package]
name = "test_rust_exportexcel"
version = "0.0.1"
authors = ["xx <xx@163.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# toolchain :stable-x86_64-pc-windows-gnu
[dependencies]
rocket = { git = "https://github.com/SergioBenitez/Rocket.git", rev  = "c24f15c18f02319be83af4f3c1951dc220b52c5e" }
simple_excel_writer = "0.1.7"
uuid = { version = "0.8", features = ["serde", "v4"] } 
[dependencies.tokio]
version = "1.0"
features = ["fs", "io-std", "io-util", "rt-multi-thread", "sync", "signal", "macros"]
[profile.release]
lto = true
opt-level = 'z'

一开始简单使用NamedFile 导出excel

#[get("/export1.xlsx")]
pub async  fn export1() -> Option<NamedFile> {
    match std::fs::create_dir("/tmp") {
        Err(why) => println!("! {:?}", why.kind()),
        Ok(_) => {},
    }
    let filename =format!("/tmp/{}.xlsx",Uuid::new_v4() ) ;
    let mut wb = Workbook::create(&filename);
    let mut sheet = wb.create_sheet("第一页");

    // set column width
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 80.0 });
    sheet.add_column(Column { width: 60.0 });

    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","XML Remark"])?;
        sw.append_row(row!["Amy", (), true,"<xml><tag>\"Hello\" & 'World'</tag></xml>"])?;
        sw.append_blank_rows(2);
        sw.append_row(row!["Tony", blank!(2), "retired"])
    }).expect("write excel error!");

    let mut sheet = wb.create_sheet("第二页");
    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","Remark"])?;
        sw.append_row(row!["Amy", "Manager", true])
    }).expect("write excel error!");

    
    wb.close().expect("close excel error!");

    NamedFile::open(&filename).await.ok()
}

后来觉得不能改导出的文件名,看了好久源码以后改成


#[get("/export2")]
pub async fn export2<'r>() -> Result<rocket::Response<'r>, rocket::http::Status> {
    match std::fs::create_dir("/tmp") {
        Err(why) => println!("! {:?}", why.kind()),
        Ok(_) => {},
    }
    let filename =format!("/tmp/{}.xlsx",Uuid::new_v4() ) ;
    let mut wb = Workbook::create(&filename);
    let mut sheet = wb.create_sheet("第一页");

    // set column width
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 30.0 });
    sheet.add_column(Column { width: 80.0 });
    sheet.add_column(Column { width: 60.0 });

    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","XML Remark"])?;
        sw.append_row(row!["Amy", (), true,"<xml><tag>\"Hello\" & 'World'</tag></xml>"])?;
        sw.append_blank_rows(2);
        sw.append_row(row!["Tony", blank!(2), "retired"])
    }).expect("write excel error!");

    let mut sheet = wb.create_sheet("第二页");
    wb.write_sheet(&mut sheet, |sheet_writer| {
        let sw = sheet_writer;
        sw.append_row(row!["Name", "Title","Success","Remark"])?;
        sw.append_row(row!["Amy", "Manager", true])
    }).expect("write excel error!");

    
    wb.close().expect("close excel error!");

    let response = Response::build()
         .raw_header("Content-Type","application/vnd.ms-excel;charset=utf-8")
         .raw_header("Content-Disposition", "attachment;filename=导出excel.xlsx")
         .chunked_body(File::open(&filename).await.unwrap(), 8096)
         .ok();
         
     response
}

这个好,java输出文件名还要先转码

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!