Overwriting a file instead of appending

Hello, I am trying to make a program that can add cells containing numbers to a preexisting xlsx file. I thought I had found a good crate for this (https://docs.rs/xlsxwriter/0.3.1/xlsxwriter) but when I tried it out, it seems that trying to write any data to a sheet overwrites the entire file and deletes all of the data in the other cells, but says that the sheet is not found. :frowning:

For example, if I try to say myworkbook.get_worksheet("sheet_one") it returns None instead of a new worksheet even though that worksheet definitely exists , and when I open the spreadsheet in in any viewer after running the program, the entire sheet is blank, and any data entered in the sheet previously is gone. What is going on here? If anyone has used this crate have you had this problem? My code is super simple, and looks like this

use xlsxwriter::{Workbook};
use xlsxwriter::XlsxError;
use std::io::Error;
use std::io::ErrorKind;

//use std::io::Error;

pub enum MyError {
    xlsx(XlsxError),
    normal(Error)
}

pub fn write_field(x: u128, y: u128, file_path: &str, sheet: &str, value: u128) -> Result<(), MyError> {
    let workbook = Workbook::new(file_path);
    let main_sheet = workbook.get_worksheet(sheet);

    if main_sheet.is_none() {
        println!("sheet not found!");
        return Err(MyError::normal(Error::new(ErrorKind::NotFound, "sheet not found")));
    }
    match main_sheet.unwrap().write_number(y as u32,x as u16, value as f64, None) {
        Ok(_) => {}
        Err(e) => {
            return Err(MyError::xlsx(e));
        }
    }
    return Ok(());
}

If anyone knows how to fix this problem, any help would be much appreciated.

I know that there are other crates to write xlsx, but xlsxwriter seems to be the one with the most features.

Also, has anyone reading this has had success editing xlsx files in rust with a different crate?

Unfortunately the library doesn't support what you're trying to do. From the documentation

Rust binding of libxlsxwriter

From libxlsxwriter's FAQ

Q. Can Libxlsxwriter use an existing Excel file as a template?

No.

Libxlsxwriter is designed only as a file writer . It cannot read or modify an existing Excel file.

Oh ok. I guess I will have to find some other way to do this.

You could manually read the file first using a different library, put all that data into Libxlsxwriter, and then make any modifications you need before writing the file back out.

Or just use a library that supports reading from file.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.