Skip to content

Go Office ライブラリ — クイックスタート

Go パッケージ github.com/yfedoseev/office_oxide/go は office_oxide の C FFI を cgo でラップし、DOCX / XLSX / PPTX / DOC / XLS / PPT を読み書き・変換・編集するための idiomatic な Go 型を提供します。

インストール

go get github.com/yfedoseev/office_oxide/go@latest

このバインディングはリンク時に office_oxide C ライブラリが必要です。提供方法は 2 通り。

オプション 1 — ワンライナーインストーラ(推奨):

go run github.com/yfedoseev/office_oxide/go/cmd/install@latest

このインストーラがあなたの OS/arch に合った prebuilt な liboffice_oxide(とヘッダ)をダウンロードし、cgo が見つけられる場所に配置します。アップグレード後の新しい ABI を取り込むには再実行してください。

オプション 2 — 自分で cgo フラグを設定(Rust ソースから cargo build --release --lib でビルド済みか、システム prefix にある場合):

export CGO_CFLAGS="-I/usr/local/include"
export CGO_LDFLAGS="-L/usr/local/lib -loffice_oxide"

ドキュメントを読む

package main

import (
    "fmt"
    "log"

    officeoxide "github.com/yfedoseev/office_oxide/go"
)

func main() {
    doc, err := officeoxide.Open("report.docx")
    if err != nil {
        log.Fatal(err)
    }
    defer doc.Close()

    text, err := doc.PlainText()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(text)
}

ワンショットヘルパー:

text, err := officeoxide.ExtractText("report.docx")

コア API

doc, err := officeoxide.Open("file.xlsx")
if err != nil { log.Fatal(err) }
defer doc.Close()

format, _ := doc.Format()      // "xlsx"
text, _   := doc.PlainText()
md, _     := doc.ToMarkdown()
html, _   := doc.ToHTML()
irJSON, _ := doc.ToIRJSON()

err = doc.SaveAs("file.docx")

Document は C ハンドルをラップします。Close を忘れるとファイナライザが解放しますが、決定的なクリーンアップのために常に defer doc.Close() を優先してください。

バイトから開く(ストリーミング/サーバーレス向け):

data, _ := os.ReadFile("report.pptx")
doc, err := officeoxide.OpenFromBytes(data, "pptx")

format"docx""xlsx""pptx""doc""xls""ppt" のいずれか。

編集

編集可能ハンドルは保存時に変更されていない OPC パーツ(画像、グラフ、カスタム XML)をすべて温存します。DOCX、XLSX、PPTX のみ。

ed, err := officeoxide.OpenEditable("template.docx")
if err != nil { log.Fatal(err) }
defer ed.Close()

n, _ := ed.ReplaceText("{{name}}", "Alice")
fmt.Printf("%d 件置換\n", n)

err = ed.Save("out.docx")

DOCX / PPTX のテキスト置換

ed, _ := officeoxide.OpenEditable("slides.pptx")
defer ed.Close()

ed.ReplaceText("Q3", "Q4")
ed.ReplaceText("2024", "2025")

buf, _ := ed.SaveToBytes()   // []byte(アップロード/ストリーム可能)
_ = os.WriteFile("slides_q4.pptx", buf, 0o644)

XLSX セルの設定

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")

NewStringCellNewNumberCellNewBoolCellNewEmptyCell を使ってください — コンストラクタが FFI 呼び出しに正しいバリアントを選びます。

フォーマット非依存の IR

doc.ToIRJSON() は Rust の DocumentIR スキーマに合致する JSON を返します。必要な形に Unmarshal してください:

import "encoding/json"

irJSON, _ := doc.ToIRJSON()

var ir struct {
    Sections []struct {
        Title    *string           `json:"title"`
        Elements []json.RawMessage `json:"elements"`
    } `json:"sections"`
}
_ = json.Unmarshal([]byte(irJSON), &ir)
fmt.Printf("%d セクション\n", len(ir.Sections))

開かずにフォーマット検出

fmt := officeoxide.DetectFormat("mystery.bin")  // 未対応なら ""

レガシーフォーマット

OOXML と同じように開けます。SaveAs は IR 経由で透過的に変換します:

doc, _ := officeoxide.Open("old.xls")
defer doc.Close()
_ = doc.SaveAs("modern.xlsx")

エラー

すべての失敗呼び出しは型付きコードと発生元オペレーションを持つ *officeoxide.Error を返します:

if _, err := officeoxide.Open("missing.docx"); err != nil {
    var e *officeoxide.Error
    if errors.As(err, &e) {
        fmt.Printf("code=%d op=%s\n", e.Code, e.Op)
    }
}

クローズ済みハンドルの使用は officeoxide.ErrClosed を返します。

Code 名前 意味
0 OK 成功
1 INVALID_ARG nil / 空 / 不正なフォーマット文字列
2 IO ファイルシステムエラー
3 PARSE 壊れたドキュメント
4 EXTRACTION パースは成功したがレンダリングが失敗
5 INTERNAL バグ — issue を上げてください
6 UNSUPPORTED 拡張子/機能が未対応

トラブルシューティング

症状 対処
could not determine kind of name for C.office_document_open C ヘッダが cgo から見えていません。インストーラを実行するか CGO_CFLAGS を設定。
リンク時に cannot find -loffice_oxide CGO_LDFLAGS="-L/path/to/lib -loffice_oxide" を設定するかインストーラを実行。
実行時 cannot open shared object file ライブラリディレクトリを LD_LIBRARY_PATH(Linux)、DYLD_LIBRARY_PATH(macOS)に追加するか、DLL をバイナリの隣にコピー(Windows)。
.doc/.xlsunsupported format 拡張子が小文字か確認、または OpenFromBytes(data, "doc") を使用。
クロスコンパイルが失敗 cgo はターゲットに合った C ツールチェーンが必要。zig ccCC=aarch64-linux-gnu-gcc を使用。

関連項目