Skip to content

在 XLSX 中写入单元格

set_cell(sheet_index, cell_ref, value) 通过从零开始的工作表索引和标准 A1 单元格引用(A1B12AA42)向工作表写入值。Office Oxide 接受字符串、数字、布尔和空值。

工作表的周边内容——格式、合并单元格、条件格式、命名区域、图表——原封不动地保留。

写入基本类型

Rust

use office_oxide::edit::EditableDocument;
use office_oxide::xlsx::edit::CellValue;

let mut wb = EditableDocument::open("budget.xlsx")?;
wb.set_cell(0, "A1", CellValue::String("Total".into()))?;
wb.set_cell(0, "B1", CellValue::Number(42.5))?;
wb.set_cell(0, "C1", CellValue::Boolean(true))?;
wb.set_cell(0, "D1", CellValue::Empty)?;
wb.save("budget.xlsx")?;

Python

from office_oxide import EditableDocument

with EditableDocument.open("budget.xlsx") as ed:
    ed.set_cell(0, "A1", "Total")     # string
    ed.set_cell(0, "B1", 42.5)        # number (int also accepted)
    ed.set_cell(0, "C1", True)        # boolean
    ed.set_cell(0, "D1", None)        # empty
    ed.save("budget.xlsx")

JavaScript

import { EditableDocument } from 'office-oxide';

using wb = EditableDocument.open('budget.xlsx');

wb.setCell(0, 'A1', 'Total');   // string
wb.setCell(0, 'B1', 42.5);      // number
wb.setCell(0, 'C1', true);      // boolean
wb.setCell(0, 'D1', null);      // empty

wb.save('budget.xlsx');

Go

ed, _ := officeoxide.OpenEditable("budget.xlsx")
defer ed.Close()

ed.SetCell(0, "A1", officeoxide.NewStringCell("Total"))
ed.SetCell(0, "B1", officeoxide.NewNumberCell(42.5))
ed.SetCell(0, "C1", officeoxide.NewBoolCell(true))
ed.SetCell(0, "D1", officeoxide.NewEmptyCell())

ed.Save("budget.xlsx")

C#

using var wb = EditableDocument.Open("budget.xlsx");

wb.SetCell(0u, "A1", "Total");        // string overload
wb.SetCell(0u, "B1", 42.5);           // double overload
wb.SetCell(0u, "C1", true);           // bool overload
wb.SetCellEmpty(0u, "D1");            // clear a cell

wb.Save("budget.xlsx");

C

int err = 0;
OfficeEditableHandle *wb = office_editable_open("budget.xlsx", &err);

/* value_type: OFFICE_CELL_EMPTY|STRING|NUMBER|BOOLEAN; value_str only for STRING */
office_editable_set_cell(wb, 0, "A1", OFFICE_CELL_STRING,  "Total", 0.0,  &err);
office_editable_set_cell(wb, 0, "B1", OFFICE_CELL_NUMBER,  NULL,    42.5, &err);
office_editable_set_cell(wb, 0, "C1", OFFICE_CELL_BOOLEAN, NULL,    1.0,  &err);  /* nonzero = true */
office_editable_set_cell(wb, 0, "D1", OFFICE_CELL_EMPTY,   NULL,    0.0,  &err);

office_editable_save(wb, "budget.xlsx", &err);
office_editable_free(wb);

批量更新

在一次打开/保存周期内完成所有写入操作。

Rust

let rows = [
    ("Acme",    120_000.0, true),
    ("Globex",   85_000.0, false),
    ("Initech",  62_500.0, true),
];

let mut ed = EditableDocument::open("dashboard.xlsx")?;
for (i, (name, revenue, active)) in rows.iter().enumerate() {
    let row = i + 2;
    ed.set_cell(0, &format!("A{row}"), CellValue::String((*name).into()))?;
    ed.set_cell(0, &format!("B{row}"), CellValue::Number(*revenue))?;
    ed.set_cell(0, &format!("C{row}"), CellValue::Boolean(*active))?;
}
ed.save("dashboard.xlsx")?;

Python

rows = [
    ("Acme",    120_000, True),
    ("Globex",   85_000, False),
    ("Initech",  62_500, True),
]

with EditableDocument.open("dashboard.xlsx") as ed:
    for i, (name, revenue, active) in enumerate(rows):
        row = i + 2  # leave row 1 for headers
        ed.set_cell(0, f"A{row}", name)
        ed.set_cell(0, f"B{row}", revenue)
        ed.set_cell(0, f"C{row}", active)
    ed.save("dashboard.xlsx")

C

const char *names[]   = { "Acme",   "Globex", "Initech" };
double      revenue[] = { 120000.0,  85000.0,  62500.0  };
int         active[]  = { 1,         0,        1        };

int err = 0;
OfficeEditableHandle *ed = office_editable_open("dashboard.xlsx", &err);
for (int i = 0; i < 3; i++) {
    char a[8], b[8], c[8];
    int row = i + 2;  /* leave row 1 for headers */
    snprintf(a, sizeof a, "A%d", row);
    snprintf(b, sizeof b, "B%d", row);
    snprintf(c, sizeof c, "C%d", row);
    office_editable_set_cell(ed, 0, a, OFFICE_CELL_STRING,  names[i], 0.0,        &err);
    office_editable_set_cell(ed, 0, b, OFFICE_CELL_NUMBER,  NULL,     revenue[i], &err);
    office_editable_set_cell(ed, 0, c, OFFICE_CELL_BOOLEAN, NULL,     active[i],  &err);
}
office_editable_save(ed, "dashboard.xlsx", &err);
office_editable_free(ed);

定位其他工作表

sheet_index 是工作簿中以零为起点的位置,而不是工作表名称。要通过名称查找索引,请先读取工作簿:

Python

from office_oxide import Document, EditableDocument

with Document.open("budget.xlsx") as doc:
    sheet_names = [s.name() for s in doc.as_xlsx().sheets()]
print(sheet_names)   # ['Summary', 'Q1', 'Q2', 'Q3', 'Q4']

idx = sheet_names.index("Q3")
with EditableDocument.open("budget.xlsx") as ed:
    ed.set_cell(idx, "B5", 42_000)
    ed.save("budget.xlsx")

set_cell 会修改什么,不会修改什么

set_cell 写入单元格的 <v> 值和 <t> 类型;它不会

  • 重新计算公式。如需触发重算,请在 Excel 中打开文件,或使用计算引擎。
  • 对 shared-strings 表做超出追加新字符串之外的修改。已有字符串继续共享。
  • 更改单元格格式、条件格式或命名区域。

若目标单元格当前包含公式,set_cell 会用静态值覆盖该公式。如需显式写入公式,请使用格式专用的 xlsx::edit API。

错误

症状 原因
OfficeError::Sheet(idx) (Rust) / IndexError (Python) sheet_index ≥ 工作簿中的工作表数量
OfficeError::CellRef("...") 单元格引用不是合法的 A1 格式
写入 Number(value) 后 Excel 显示单元格为空 该单元格之前被格式化为文本——在 Excel 中清除格式,或通过格式专用 API 写入

相关链接