1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! xlsx を作って読み戻すところ
use folio::book::{Book, Writer};
use folio::cell::{Cell, Value};
use folio::date::{self, Moment};
use folio::style::Format;
use std::path::PathBuf;
/// 試しに使うファイルの置き場。target の下なので消えても差し支えない
fn place(name: &str) -> PathBuf {
let mut path = PathBuf::from("target");
path.push(format!("book-{name}.xlsx"));
path
}
/// シートを読み切って、行番号ごとの値にする
fn collect(book: &mut Book, name: &str) -> Vec<(u32, Vec<(u32, Value)>)> {
let mut sheet = book.read(name).unwrap();
let mut result = Vec::new();
while let Some(row) = sheet.read().unwrap() {
let cell = row.cell.iter().map(|one| (one.column, one.value.clone())).collect();
result.push((row.number, cell));
}
result
}
#[test]
fn values_come_back_as_they_were_written() {
let path = place("value");
let mut writer = Writer::create(&path, &["データ"]).unwrap();
writer.start("データ").unwrap();
writer.row(&["名前".into(), 3.5.into(), true.into()]).unwrap();
writer.row(&["記号 <&>\"'".into(), (-1).into(), false.into()]).unwrap();
writer.row(&["改行\nあり".into(), 1234567890123i64.into()]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let row = collect(&mut book, "データ");
assert_eq!(row.len(), 3);
assert_eq!(row[0].1[0].1, Value::Text("名前".to_string()));
assert_eq!(row[0].1[1].1, Value::Number(3.5));
assert_eq!(row[0].1[2].1, Value::Boolean(true));
assert_eq!(row[1].1[0].1, Value::Text("記号 <&>\"'".to_string()));
assert_eq!(row[1].1[1].1, Value::Number(-1.0));
assert_eq!(row[2].1[0].1, Value::Text("改行\nあり".to_string()));
assert_eq!(row[2].1[1].1, Value::Number(1234567890123.0));
}
#[test]
fn several_sheets_keep_their_order_and_names() {
let path = place("sheet");
let mut writer = Writer::create(&path, &["一枚目", "二枚目", "三枚目"]).unwrap();
writer.start("二枚目").unwrap();
writer.row(&["に".into()]).unwrap();
writer.start("一枚目").unwrap();
writer.row(&["いち".into()]).unwrap();
writer.start("三枚目").unwrap();
writer.row(&["さん".into()]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let name: Vec<String> = book.sheet().iter().map(|one| one.name.clone()).collect();
assert_eq!(name, vec!["一枚目", "二枚目", "三枚目"]);
assert_eq!(collect(&mut book, "一枚目")[0].1[0].1, Value::Text("いち".to_string()));
assert_eq!(collect(&mut book, "三枚目")[0].1[0].1, Value::Text("さん".to_string()));
}
#[test]
fn a_date_comes_back_as_the_same_moment() {
let path = place("date");
let when = Moment {year: 2026, month: 9, day: 8, hour: 13, minute: 45, second: 30};
let day = Moment {year: 1900, month: 1, day: 1, hour: 0, minute: 0, second: 0};
let mut writer = Writer::create(&path, &["日付"]).unwrap();
writer.start("日付").unwrap();
writer.place(1, &[
Cell::styled(1, date::serial(&when, false).into(), Format::DateTime.index()),
Cell::styled(2, date::serial(&day, false).into(), Format::Date.index()),
Cell::new(3, 45000.into()),
]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let mut sheet = book.read("日付").unwrap();
let style = sheet.style();
let row = sheet.read().unwrap().unwrap();
assert!(style.is_date(row.cell[0].style));
assert!(style.is_date(row.cell[1].style));
assert!(!style.is_date(row.cell[2].style));
let Value::Number(serial) = row.cell[0].value else {panic!("数ではありません")};
assert_eq!(date::moment(serial, false), when);
let Value::Number(serial) = row.cell[1].value else {panic!("数ではありません")};
assert_eq!(date::moment(serial, false), day);
}
#[test]
fn a_formula_is_kept_with_its_value() {
let path = place("formula");
let mut writer = Writer::create(&path, &["式"]).unwrap();
writer.start("式").unwrap();
writer.place(1, &[
Cell::new(1, 2.into()),
Cell {column: 2, style: 0, value: Value::Number(4.0), formula: "A1*2".to_string()},
]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let mut sheet = book.read("式").unwrap();
let row = sheet.read().unwrap().unwrap();
assert_eq!(row.cell[1].formula, "A1*2");
assert_eq!(row.cell[1].value, Value::Number(4.0));
}
#[test]
fn rows_and_columns_can_be_left_out() {
let path = place("sparse");
let mut writer = Writer::create(&path, &["とびとび"]).unwrap();
writer.start("とびとび").unwrap();
writer.place(5, &[Cell::new(3, "み".into())]).unwrap();
writer.place(100, &[Cell::new(1, "ひゃく".into()), Cell::new(50, "ごじゅう".into())]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let row = collect(&mut book, "とびとび");
assert_eq!(row.len(), 2);
assert_eq!(row[0].0, 5);
assert_eq!(row[0].1, vec![(3, Value::Text("み".to_string()))]);
assert_eq!(row[1].0, 100);
assert_eq!(row[1].1[1], (50, Value::Text("ごじゅう".to_string())));
}
#[test]
fn a_column_can_be_found_by_its_number() {
let path = place("at");
let mut writer = Writer::create(&path, &["引き"]).unwrap();
writer.start("引き").unwrap();
writer.place(1, &[Cell::new(2, "に".into()), Cell::new(7, "なな".into())]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let mut sheet = book.read("引き").unwrap();
let row = sheet.read().unwrap().unwrap();
assert_eq!(row.at(7).unwrap().value, Value::Text("なな".to_string()));
assert!(row.at(3).is_none());
}
#[test]
fn many_rows_go_in_and_come_back() {
let path = place("many");
let count = 120000u32;
let mut writer = Writer::create(&path, &["大"]).unwrap();
writer.start("大").unwrap();
for row in 1..=count {
writer.row(&[
format!("名前{}", row % 997).into(),
(row as i64).into(),
(row as f64 * 1.5).into(),
]).unwrap();
}
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let mut sheet = book.read("大").unwrap();
let mut seen = 0u32;
let mut total = 0.0;
while let Some(row) = sheet.read().unwrap() {
seen += 1;
assert_eq!(row.number, seen);
assert_eq!(row.cell.len(), 3);
assert_eq!(row.cell[0].value, Value::Text(format!("名前{}", seen % 997)));
if let Value::Number(number) = row.cell[1].value {
total += number;
}
}
assert_eq!(seen, count);
assert_eq!(total, (count as f64) * (count as f64 + 1.0) / 2.0);
}
#[test]
fn editing_keeps_the_parts_that_were_not_touched() {
let source_path = place("source");
let target_path = place("edited");
let mut writer = Writer::create(&source_path, &["のこす", "なおす"]).unwrap();
writer.start("のこす").unwrap();
writer.row(&["そのまま".into(), 1.into()]).unwrap();
writer.start("なおす").unwrap();
writer.row(&["まえ".into(), 2.into()]).unwrap();
writer.finish().unwrap();
let source = Book::open(&source_path).unwrap();
let mut writer = Writer::edit(source, &target_path, &["なおす"]).unwrap();
writer.start("なおす").unwrap();
writer.row(&["あと".into(), 99.into()]).unwrap();
writer.row(&["ふえた行".into()]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&target_path).unwrap();
let name: Vec<String> = book.sheet().iter().map(|one| one.name.clone()).collect();
assert_eq!(name, vec!["のこす", "なおす"]);
let keep = collect(&mut book, "のこす");
assert_eq!(keep[0].1[0].1, Value::Text("そのまま".to_string()));
assert_eq!(keep[0].1[1].1, Value::Number(1.0));
let fixed = collect(&mut book, "なおす");
assert_eq!(fixed.len(), 2);
assert_eq!(fixed[0].1[0].1, Value::Text("あと".to_string()));
assert_eq!(fixed[0].1[1].1, Value::Number(99.0));
assert_eq!(fixed[1].1[0].1, Value::Text("ふえた行".to_string()));
}
#[test]
fn a_sheet_that_was_not_declared_cannot_be_written() {
let path = place("unknown");
let mut writer = Writer::create(&path, &["ある"]).unwrap();
assert!(writer.start("ない").is_err());
}
#[test]
fn a_row_cannot_go_backwards() {
let path = place("backwards");
let mut writer = Writer::create(&path, &["順"]).unwrap();
writer.start("順").unwrap();
writer.place(10, &[Cell::new(1, 1.into())]).unwrap();
assert!(writer.place(5, &[Cell::new(1, 2.into())]).is_err());
}
#[test]
fn a_row_beyond_the_limit_is_an_error() {
let path = place("limit");
let mut writer = Writer::create(&path, &["上限"]).unwrap();
writer.start("上限").unwrap();
assert!(writer.place(1048577, &[Cell::new(1, 1.into())]).is_err());
}
#[test]
fn a_missing_sheet_is_an_error() {
let path = place("missing");
let mut writer = Writer::create(&path, &["ある"]).unwrap();
writer.start("ある").unwrap();
writer.row(&[1.into()]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
assert!(book.read("ない").is_err());
}
/// 列幅と結合セルの入った、手で組んだ xlsx を置く
///
/// folio は列幅も結合セルも作れないので、直しても残ることを確かめるには、
/// あらかじめ入ったファイルが要る。
fn build_with_extras(path: &std::path::Path) {
let head = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
let main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
let relation = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
let base = "application/vnd.openxmlformats-officedocument.spreadsheetml";
let sheet = format!(
"{head}<worksheet xmlns=\"{main}\" xmlns:r=\"{relation}\">\
<cols><col min=\"1\" max=\"1\" width=\"24\" customWidth=\"1\"/></cols>\
<sheetData><row r=\"1\"><c r=\"A1\" t=\"inlineStr\"><is><t>まえ</t></is></c></row></sheetData>\
<mergeCells count=\"1\"><mergeCell ref=\"A8:C8\"/></mergeCells>\
<pageMargins left=\"0.7\" right=\"0.7\" top=\"0.75\" bottom=\"0.75\" header=\"0.3\" footer=\"0.3\"/>\
</worksheet>"
);
let types = format!(
"{head}<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">\
<Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/>\
<Default Extension=\"xml\" ContentType=\"application/xml\"/>\
<Override PartName=\"/xl/workbook.xml\" ContentType=\"{base}.sheet.main+xml\"/>\
<Override PartName=\"/xl/worksheets/sheet1.xml\" ContentType=\"{base}.worksheet+xml\"/>\
</Types>"
);
let root = format!(
"{head}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
<Relationship Id=\"rId1\" Type=\"{relation}/officeDocument\" Target=\"xl/workbook.xml\"/>\
</Relationships>"
);
let workbook = format!(
"{head}<workbook xmlns=\"{main}\" xmlns:r=\"{relation}\">\
<sheets><sheet name=\"もと\" sheetId=\"1\" r:id=\"rId1\"/></sheets></workbook>"
);
let link = format!(
"{head}<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\
<Relationship Id=\"rId1\" Type=\"{relation}/worksheet\" Target=\"worksheets/sheet1.xml\"/>\
</Relationships>"
);
let mut writer = folio::zip::Writer::create(path).unwrap();
writer.add("[Content_Types].xml", types.as_bytes()).unwrap();
writer.add("_rels/.rels", root.as_bytes()).unwrap();
writer.add("xl/workbook.xml", workbook.as_bytes()).unwrap();
writer.add("xl/_rels/workbook.xml.rels", link.as_bytes()).unwrap();
writer.add("xl/worksheets/sheet1.xml", sheet.as_bytes()).unwrap();
writer.finish().unwrap();
}
#[test]
fn editing_a_sheet_keeps_what_is_outside_the_rows() {
let source_path = place("extras-source");
let target_path = place("extras-target");
build_with_extras(&source_path);
let source = Book::open(&source_path).unwrap();
let mut writer = Writer::edit(source, &target_path, &["もと"]).unwrap();
writer.start("もと").unwrap();
writer.row(&["あと".into(), 42.into()]).unwrap();
writer.finish().unwrap();
// 行は書き直したものになっている
let mut book = Book::open(&target_path).unwrap();
let row = collect(&mut book, "もと");
assert_eq!(row.len(), 1);
assert_eq!(row[0].1[0].1, Value::Text("あと".to_string()));
assert_eq!(row[0].1[1].1, Value::Number(42.0));
// sheetData の外はそのまま残っている
let part = String::from_utf8(book.package().unwrap().read("xl/worksheets/sheet1.xml").unwrap()).unwrap();
assert!(part.contains("<col min=\"1\" max=\"1\" width=\"24\""), "{part}");
assert!(part.contains("<mergeCell ref=\"A8:C8\"/>"), "{part}");
assert!(part.contains("<pageMargins"), "{part}");
assert!(!part.contains("まえ"), "{part}");
}
#[test]
fn a_declared_sheet_that_was_never_written_is_still_there() {
let path = place("untouched");
let mut writer = Writer::create(&path, &["書く", "書かない"]).unwrap();
writer.start("書く").unwrap();
writer.row(&["ある".into()]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&path).unwrap();
let name: Vec<String> = book.sheet().iter().map(|one| one.name.clone()).collect();
assert_eq!(name, vec!["書く", "書かない"]);
assert!(collect(&mut book, "書かない").is_empty());
}
#[test]
fn a_sheet_marked_for_editing_but_left_alone_keeps_its_rows() {
let source_path = place("left-source");
let target_path = place("left-target");
let mut writer = Writer::create(&source_path, &["いち", "に"]).unwrap();
writer.start("いち").unwrap();
writer.row(&["もとのまま".into()]).unwrap();
writer.start("に").unwrap();
writer.row(&["こちらも".into()]).unwrap();
writer.finish().unwrap();
let source = Book::open(&source_path).unwrap();
let writer = Writer::edit(source, &target_path, &["いち", "に"]).unwrap();
writer.finish().unwrap();
let mut book = Book::open(&target_path).unwrap();
assert_eq!(collect(&mut book, "いち")[0].1[0].1, Value::Text("もとのまま".to_string()));
assert_eq!(collect(&mut book, "に")[0].1[0].1, Value::Text("こちらも".to_string()));
}