Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.098.9 KB2026-09-14
Version
0.1.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
98.9 KB
Downloads
1
Checksum
bdac84a1e4fe4dd3505b93c2781b1f15833b5189c2e4ee976225fa3c512885cc
Dependencies
None

style.rs

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
//! 書式
//!
//! セルの `s` は `xl/styles.xml` の `cellXfs` の何番目かを指し、そこから表示形式の番号 (numFmtId) が決まる。
//! folio が読むのはこの一本の道だけである。フォントや罫線は読まないが、
//! 直さないファイルではパートごとそのまま写すので、失われることはない。
//!
//! # 日付かどうか
//!
//! xlsx のセルに日付という型はない。日付は数で入っていて、表示形式が日付なら日付として読む。
//! だから [`Style::is_date`] を見ずに数だけ取ると、日付は 45000 のような数になる。

use crate::error::Error;
use crate::xml::{Event, Reader};
use std::collections::HashMap;


/// 決まった番号のうち、日付や時刻を表すもの
const DATE_FORMAT: [u32; 25] = [
    14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 50, 57,
    58,
];

/// folio が作るファイルで使う、自前の表示形式
const OWN_FORMAT: [(u32, &str); 3] = [
    (164, "yyyy\\-mm\\-dd"),
    (165, "hh:mm:ss"),
    (166, "yyyy\\-mm\\-dd\\ hh:mm:ss"),
];


/// folio が作るファイルで選べる書式
///
/// 番号は folio が書く styles.xml の cellXfs の位置にあたる。
/// 他所で作られたファイルを直すときは、そのファイルの書式が別に並んでいるので、これは使えない。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    /// そのまま
    General = 0,
    /// 整数
    Integer = 1,
    /// 小数 2 桁
    Decimal = 2,
    /// 日付
    Date = 3,
    /// 時刻
    Time = 4,
    /// 日付と時刻
    DateTime = 5,
    /// 百分率
    Percent = 6,
    /// 文字として扱う
    Text = 7,
}


impl Format {
    /// cellXfs での位置
    pub fn index(self) -> u32 {
        self as u32
    }
}


/// styles.xml から読んだ、書式の対応
pub struct Style {
    /// cellXfs の各項目が指す表示形式の番号
    format: Vec<u32>,
    /// そのファイルが自前で決めた表示形式
    code: HashMap<u32, String>,
}


impl Style {
    /// 何も入っていない対応
    pub fn new() -> Style {
        Style {format: Vec::new(), code: HashMap::new()}
    }

    /// styles.xml を読む
    ///
    /// `<xf>` は `cellXfs` と `cellStyleXfs` の両方に出てくる。セルが指すのは `cellXfs` のほうだけである。
    pub fn read(reader: &mut Reader) -> Result<Style, Error> {
        let mut result = Style::new();
        let mut inside = false;

        while let Some(event) = reader.next()? {
            if event == Event::Close {
                if reader.name() == "cellXfs" {
                    inside = false;
                }

                continue;
            }

            if event != Event::Open && event != Event::Empty {
                continue;
            }

            match reader.name() {
                "cellXfs" => inside = event == Event::Open,

                "numFmt" => {
                    let id = number(reader.attribute("numFmtId"));
                    let code = reader.attribute("formatCode").unwrap_or("").to_string();
                    result.code.insert(id, code);
                }

                "xf" => {
                    if inside {
                        result.format.push(number(reader.attribute("numFmtId")));
                    }
                }

                _ => {}
            }
        }

        Ok(result)
    }

    /// 表示形式の文字列を足す
    ///
    /// xlsx では styles.xml から読むが、旧形式では FORMAT レコードから来る。
    pub fn put_format(&mut self, id: u32, code: &str) {
        self.code.insert(id, code.to_string());
    }

    /// 書式の並びに 1 つ足す。足した順が、セルの指す番号になる
    pub fn put_xf(&mut self, format: u32) {
        self.format.push(format);
    }

    /// cellXfs の位置から表示形式の番号を引く
    pub fn format_of(&self, style: u32) -> u32 {
        match self.format.get(style as usize) {
            Some(value) => *value,
            None => 0,
        }
    }

    /// cellXfs の位置から表示形式の文字列を引く
    pub fn code_of(&self, style: u32) -> Option<&str> {
        let id = self.format_of(style);

        if let Some(code) = self.code.get(&id) {
            return Some(code);
        }

        builtin(id)
    }

    /// その書式のセルを日付として読むべきか
    pub fn is_date(&self, style: u32) -> bool {
        let id = self.format_of(style);

        if DATE_FORMAT.contains(&id) {
            return true;
        }

        // 自前の表示形式は、文字列を見て決める
        match self.code.get(&id) {
            Some(code) => has_date(code),
            None => false,
        }
    }
}


impl Default for Style {
    fn default() -> Style {
        Style::new()
    }
}


/// folio が作るファイルの styles.xml
pub fn xml() -> String {
    let mut result = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
    result.push_str("<styleSheet xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\">");
    result.push_str(&format!("<numFmts count=\"{}\">", OWN_FORMAT.len()));

    for (id, code) in OWN_FORMAT {
        result.push_str(&format!("<numFmt numFmtId=\"{id}\" formatCode=\"{code}\"/>"));
    }

    result.push_str("</numFmts>");
    result.push_str("<fonts count=\"1\"><font><sz val=\"11\"/><name val=\"Calibri\"/></font></fonts>");
    result.push_str("<fills count=\"2\"><fill><patternFill patternType=\"none\"/></fill>");
    result.push_str("<fill><patternFill patternType=\"gray125\"/></fill></fills>");
    result.push_str("<borders count=\"1\"><border><left/><right/><top/><bottom/><diagonal/></border></borders>");
    result.push_str("<cellStyleXfs count=\"1\"><xf numFmtId=\"0\" fontId=\"0\" fillId=\"0\" borderId=\"0\"/></cellStyleXfs>");

    let order = [0, 1, 2, 164, 165, 166, 10, 49];
    result.push_str(&format!("<cellXfs count=\"{}\">", order.len()));

    for id in order {
        result.push_str(&format!(
            "<xf numFmtId=\"{id}\" fontId=\"0\" fillId=\"0\" borderId=\"0\" xfId=\"0\" applyNumberFormat=\"1\"/>"
        ));
    }

    result.push_str("</cellXfs>");
    result.push_str("<cellStyles count=\"1\"><cellStyle name=\"Normal\" xfId=\"0\" builtinId=\"0\"/></cellStyles>");
    result.push_str("</styleSheet>");
    result
}


/// 表示形式の文字列に、日付や時刻を出す指定が入っているか
///
/// 引用符と `\` の後ろ、`[]` の中は飾りなので見ない。
fn has_date(code: &str) -> bool {
    let mut quoted = false;
    let mut bracket = false;
    let mut escaped = false;

    for value in code.chars() {
        if escaped {
            escaped = false;
            continue;
        }

        match value {
            '\\' => escaped = true,
            '"' => quoted = !quoted,
            '[' if !quoted => bracket = true,
            ']' if !quoted => bracket = false,
            _ if quoted || bracket => {}
            'y' | 'Y' | 'd' | 'D' | 'h' | 'H' | 's' | 'S' | 'm' | 'M' => return true,
            _ => {}
        }
    }

    false
}


/// 数として読む。読めなければ 0
fn number(value: Option<&str>) -> u32 {
    match value {
        Some(text) => text.trim().parse().unwrap_or(0),
        None => 0,
    }
}


/// はじめから決まっている表示形式
pub fn builtin(id: u32) -> Option<&'static str> {
    let code = match id {
        0 => "General",
        1 => "0",
        2 => "0.00",
        3 => "#,##0",
        4 => "#,##0.00",
        9 => "0%",
        10 => "0.00%",
        11 => "0.00E+00",
        12 => "# ?/?",
        13 => "# ??/??",
        14 => "mm-dd-yy",
        15 => "d-mmm-yy",
        16 => "d-mmm",
        17 => "mmm-yy",
        18 => "h:mm AM/PM",
        19 => "h:mm:ss AM/PM",
        20 => "h:mm",
        21 => "h:mm:ss",
        22 => "m/d/yy h:mm",
        37 => "#,##0 ;(#,##0)",
        38 => "#,##0 ;[Red](#,##0)",
        39 => "#,##0.00;(#,##0.00)",
        40 => "#,##0.00;[Red](#,##0.00)",
        45 => "mm:ss",
        46 => "[h]:mm:ss",
        47 => "mmss.0",
        48 => "##0.0E+0",
        49 => "@",
        _ => return None,
    };

    Some(code)
}