現在フリーランスエンジニアとして活動していて、今今携わっている案件ではRustとTauriを使ってExcelファイルを出力するデスクトップアプリを開発しています。

プログラムからExcelファイルを操作する際に金額の桁数が大きかったり文字数が多かったりした場合、「#####」になったり見切れたりすることがあったので、Excelの行の高さと列の幅を変更する方法を調べました。

前回の記事から引き続き、今回もExcelファイルを書き込むためのライブラリとしてrust_xlsxwriterを使用します。

rust_xlsxwriterで行の高さを変更するにはset_row_height_pixelsメソッドを使用します。第一引数に行番号、第二引数には行の高さ(ピクセル)を渡します。

pub fn set_row_height_pixels(
    &mut self,
    row: RowNum,
    height: u16
) -> Result<&mut Worksheet, XlsxError>
Set the height for a row of cells, in pixels.

The set_row_height_pixels() method is used to change the default height of a row. The height is specified in pixels, where the default height is 20.

To specify the height in Excels character units use the set_row_height() method.

Arguments
  row - The zero indexed row number.
  height - The row height in pixels.

Errors
  XlsxError::RowColumnLimitError - Row exceeds Excels worksheet limits.

 

同様に列の幅を変更するにはset_column_width_pixelsメソッドを使用します。第一引数に行番号、第二引数には列の幅(ピクセル)を渡します。

pub fn set_column_width_pixels(
    &mut self,
    col: ColNum,
    width: u16
) -> Result<&mut Worksheet, XlsxError>
Set the width for a worksheet column in pixels.

The set_column_width() method is used to change the default width of a worksheet column.

To set the width in Excel character units use the set_column_width() method.

See also the autofit() method.

Arguments
  col - The zero indexed column number.
  width - The row width in pixels.

Errors
  XlsxError::RowColumnLimitError - Column exceeds Excels worksheet limits.

 

行の高さを100px、列の幅を200pxに変更するサンプルコードを載せます。

let mut book = Workbook::new();
let sheet = book.add_worksheet();
let currency_format = Format::new().set_num_format("€#,##0.00");

sheet.write_number_with_format(0, 0, 1234.5, &currency_format)?;
// 行の高さを100pxに設定
sheet.set_row_height_pixels(0, 100)?;
// 列の幅を200pxに設定
sheet.set_column_width_pixels(0, 200)?;

book.save(Path::new("test.xlsx"))?;
スクリーンショット 2023-05-01 19.33.45.png

無事RustでもExcelで行の高さと列の幅を変更することができました。

广告
将在 10 秒后关闭
bannerAds