轉換器:最簡單的一行,最靈活的任何環境
converter 套件的 Aspose.Cells for Go via C++ Toolkits 將所有「將試算表轉換為其他格式」的需求縮減為 單一入口函式:
converter.Convert(source, saveOption, sink) error
它只有三個參數,且每個參數恰好回答一個問題:
| 參數 | 類型 | 它回答的問題 | 典型值 |
|---|---|---|---|
source | datasource.DataSource | 輸入來自哪裡? | FilePathSource(path), BytesSource(data), NewReaderSource(r) |
saveOption | saveoptions.SaveOption | 輸出為何,如何調整? | formats.Get("pdf") 用於按名稱的預設值,或 pdf.New(pdf.WithOnePagePerSheet(true)) 用於精細控制 |
sink | datasource.DataSink | 輸出到哪裡? | FilePathSink(path), &BytesSink{}, NewWriterSink(w) |
對於 最簡潔 的風格,使用三個軸的預設值;對於 最彈性 的風格,則分別獨立調整每個旋鈕。由於這三個軸是獨立的,同一個 Convert 自然適用於檔案、記憶體、HTTP 和批次環境。(另外還有一個傳統的一行程式 ConvertSpreadsheetToFile,用於純檔案→檔案的情況——在下文第 1 節中比較。)本文其餘部分從最簡潔走向最彈性,逐步擴展前面的程式碼片段,而不是切換到不同的 API。
1. 最簡單:一次調用對應一種格式
1.1 內建的檔案→檔案單行程式: ConvertSpreadsheetToFile
此套件還提供一個較舊且更簡短的入口,用於經典的「將此檔案轉換為該檔案」情況。只需要兩個路徑:
package main
import (
"log"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/core"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/converter"
_ "github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/register" // registers every output format
)
func main() {
defer core.Cleanup()
// Both ends are files; the output format is inferred from the extension.
if err := converter.ConvertSpreadsheetToFile("input.xlsx", "output.pdf"); err != nil {
log.Fatal(err)
}
}
已棄用。
ConvertSpreadsheetToFile是為了向後相容性而保留的薄封裝;新程式碼請改用下方的converter.Convert。對於 file→file 情況,兩者完全等價——這就是ConvertSpreadsheetToFile所做的全部:
opt := formats.Get(strings.TrimPrefix(filepath.Ext("output.pdf"), ".")) // "pdf"
converter.Convert(
datasource.FilePathSource("input.xlsx"), // input: a file
opt, // format: taken from the extension
datasource.FilePathSink("output.pdf"), // output: a file
)
ConvertSpreadsheetToFile 和上面的 Convert 形式產生相同的結果;不同之處在於情境,如下所示。
1.2 推薦的一行程式碼:Convert 使用預設值
package main
import (
"log"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/core"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/converter"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/datasource"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/saveoptions/pdf"
)
func main() {
defer core.Cleanup()
if err := converter.Convert(
datasource.FilePathSource("input.xlsx"), // input: a file
pdf.New(), // format: PDF, all defaults
datasource.FilePathSink("output.pdf"), // output: a file
); err != nil {
log.Fatal(err)
}
}
所有三個參數均使用預設值:輸入 = 檔案,格式 = pdf.New()(無任何設定),輸出 = 檔案。這就是「最簡潔」的形態——無需手動 os.Open/os.Create,無需物件分配,無需關閉句柄;來源/匯出會為您管理資源。
1.3 兩個 file→file 形狀的比較
ConvertSpreadsheetToFile(in, out) | converter.Convert(source, opt, sink) | |
|---|---|---|
| Input | 僅檔案路徑 | 任何 DataSource:路徑、[]byte 或 reader |
| Output | 僅檔案路徑 | 任何 DataSink:路徑、位元組或 io.Writer |
| Output format | 始終根據副檔名推斷,只使用預設值 | 任何 saveOption:預設或特定格式的調整 |
| Extra import | 需要註冊格式(_ "…/register",或相應的 saveoptions/* 子套件) | 無,當您傳入如 pdf.New() 的建構函式時 |
| Status | 已棄用的薄封裝(穩定,保留以兼容) | 新程式碼的唯一文件化入口點 |
相同檔案→檔案結果,兩種不同情況:
ConvertSpreadsheetToFile— 你實際上只有兩條路徑,且對引擎的目標格式預設設定感到滿意。非常適合一次性轉換腳本、遷移批次和測試輔助工具。其代價是:輸入、輸出和設定永遠不能脫離「檔案路徑 + 預設」的形態——而且已被棄用。converter.Convert— 你想要相同的一行程式碼,但三個參數中的任何一個都可以被替換:明天輸入可能是上傳的[]byte,目標可能需要pdf.WithOnePagePerSheet(true),或是輸出直接寫入 HTTP 回應。這正是第 3 章和第 4 章的情境——使用Convert寫一次,之後的每次變更只需修改一個參數。
2. 最簡單的 × N:一個函式支援全部 32 種格式
下一層的簡潔性是使用 相同的函式,無論目標格式為何。因為 saveOption 可以根據輸出檔案的副檔名計算得出,將此推斷抽離出來即可得到一個「通用檔案轉換器」:
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/core"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/converter"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/datasource"
toolkiterrors "github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/errors"
"github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/formats"
_ "github.com/aspose-cells/aspose-cells-go-cpp-toolkits/v26/register" // registers every output format
)
// convert re-saves in as out; the output format is read from out's extension.
// The same code handles every built-in format (pdf/csv/html/md/xlsx/png/…).
// It is exactly what the deprecated ConvertSpreadsheetToFile does internally.
func convert(in, out string) error {
opt := formats.Get(strings.TrimPrefix(filepath.Ext(out), ".")) // ".pdf" -> "pdf"
if opt == nil {
return fmt.Errorf("%w: %q", toolkiterrors.ErrUnsupportedFormat, filepath.Ext(out))
}
return converter.Convert(
datasource.FilePathSource(in), // where the input comes from
opt, // what to produce: decided by the extension
datasource.FilePathSink(out), // where the output goes
)
}
func main() {
defer core.Cleanup()
if len(os.Args) != 3 {
log.Fatalf("usage: %s <input.xlsx> <output.ext>", os.Args[0])
}
if err := convert(os.Args[1], os.Args[2]); err != nil {
if errors.Is(err, toolkiterrors.ErrUnsupportedFormat) {
log.Printf("no registered output format for %q", filepath.Ext(os.Args[2]))
}
log.Fatal(err)
}
fmt.Println("done")
}
使用方式保持相同 — 只有輸出副檔名會變更:
$ go run . input.xlsx report.pdf # to PDF
$ go run . input.xlsx report.csv # to CSV
$ go run . input.xlsx report.html # to HTML
$ go run . input.xlsx notes.md # to Markdown
$ go run . input.xlsx sheet.png # to a PNG image
$ go run . input.xlsx legacy.xls # to legacy Excel
那個空白的 _ "…/register" 匯入是什麼?
有兩種方法可以取得 saveOption;這是「最簡潔」風格需要了解的唯一概念:
- 從註冊表中根據格式名稱查找 (
formats.Get):擴展必須存在於formats註冊表中。每個saveoptions/*子套件會在自己的init()中註冊,但僅在被匯入時。逐一匯入您需要的子套件(例如只匯入pdf,如果您要轉換為 PDF),或 空白匯入…/register一次,它會一次註冊所有 32 種格式——上面的「通用轉換器」依賴於這一行。 - 直接呼叫建構函式 (
pdf.New(),markdown.New()):繞過註冊表,不需要register匯入;代價是每使用一種格式就需要一行匯入。
簡而言之:只有在透過 formats.Get 加上輸出副檔名來解析時才使用 _ "…/register";直接傳遞建構函式則不需要額外的操作。空白匯入是無害的,且在官方範例中總是會出現。
3. 最靈活的:獨立調整每個旋鈕
當需求超出「檔案到檔案的預設設定」時,您不需要更改 API —— 三個 Convert 參數可以獨立互換。
1. 輸入(來源):從檔案、到記憶體、到任何串流
datasource.FilePathSource("input.xlsx") // a file on disk
datasource.BytesSource(data) // []byte already in memory (downloads, cached reuse)
datasource.NewReaderSource(r.Body) // any io.Reader (HTTP body, compressed stream, …)
注意:底層引擎需要對整個內容進行隨機存取,因此
ReaderSource在首次存取時會完整緩衝串流;之後的每次Open都會提供該緩衝的副本。可放心於 HTTP 中使用,但需了解它並非真正的 “在串流時轉換”。
2. 格式 (saveOption):預設,或已調整
| Scenario | Writing style | Why |
|---|---|---|
| 某些使用預設設定的格式 | formats.Get("pdf") | 根據副檔名查找;不區分大小寫;nil 若未註冊 |
| 具有特定格式選項的格式 | pdf.New(pdf.WithOnePagePerSheet(true)) | 功能選項 |
| 預設設定,明確指定格式 | ooxml.New() / csv.New() / … | 每種格式都有一個零參數建構函式 |
| 自訂私有格式 | formats.Register("fmt", factory) | 插入註冊表 — 參見 docs/register.md |
功能選項僅出現在具有此類選項的格式上:PDF 中每個工作表一頁的選項是 WithOnePagePerSheet;HTML 中內嵌圖像的選項是 WithExportImagesAsBase64;TSV 的選項是 formats.Get("tsv")。選項採用指標語義:省略即使用引擎的預設值;明確傳遞 false 也算作設定。
3. 輸出 (sink):檔案、位元組或 io.Writer
datasource.FilePathSink("output.pdf") // to disk (parent dirs are created)
&out // into memory; read it back with out.Bytes()
datasource.NewWriterSink(w) // straight into any io.Writer (http.ResponseWriter, buffer, socket)
BytesSink 與 WriterSink 是「最靈活」的兩個關鍵:它們讓轉換結果完全跳過磁碟,直接流入 HTTP 回應、物件儲存、ZIP 等等。這三者都是相同 sink 參數的不同實作,因此任何接受 []byte 或 io.Writer 的項目都可以插入轉換器中使用。
4. 實際環境示例:一個 Convert,多個形狀
A. 在記憶體中轉換;下載端點串流 PDF
常見的伺服器端情境 — 使用者上傳 xlsx,端點回傳 PDF,且不產生暫存檔案:
func handleExcelToPDF(w http.ResponseWriter, r *http.Request) {
var out datasource.BytesSink
if err := converter.Convert(
datasource.NewReaderSource(r.Body), // input: the request body
pdf.New(pdf.WithOnePagePerSheet(true)), // format: PDF, one page per sheet
&out, // output: memory
); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/pdf")
w.Header().Set("Content-Disposition", `attachment; filename="report.pdf"`)
_, _ = w.Write(out.Bytes())
}
若要改為提供 CSV / Excel / HTML,僅需交換 saveOption(例如 formats.Get("csv"));其他皆不變。
B. 一次讀取,批量匯出為多種格式
只讀取一次輸入,然後透過 BytesSource 重複使用,以產生任意數量的輸出 — 非常適合「匯出每份報告」:
data, err := os.ReadFile("input.xlsx")
if err != nil {
log.Fatal(err)
}
for _, ext := range []string{"pdf", "csv", "html", "json", "md"} {
var out datasource.BytesSink
if err := converter.Convert(datasource.BytesSource(data), formats.Get(ext), &out); err != nil {
log.Fatalf("%s: %v", ext, err)
}
if err := os.WriteFile("output."+ext, out.Bytes(), 0o644); err != nil {
log.Fatal(err)
}
}
C. “另存為” 在試算表系列中(遷移 / 相容性)
在試算表家族內的格式遷移,例如 xlsx → xls、xlsx → xlsb、xlsx → ods,以及模板 xltx/xltm — 仍然只有一個 Convert,僅 saveOption 會變更:
src := datasource.FilePathSource("input.xlsx")
converter.Convert(src, formats.Get("xls"), datasource.FilePathSink("legacy.xls")) // legacy Excel
converter.Convert(src, formats.Get("xlsb"), datasource.FilePathSink("binary.xlsb")) // binary Excel
converter.Convert(src, formats.Get("ods"), datasource.FilePathSink("open.ods")) // OpenDocument
converter.Convert(src, formats.Get("xltx"), datasource.FilePathSink("template.xltx")) // template
D. 根據格式微調選項,僅在需要時
當您需要精細控制時,功能選項會出現 — 請注意以下每個調用都是實際且正確類型的:
// PDF: one page per worksheet + a compliance level
pdf.New(
pdf.WithOnePagePerSheet(true),
pdf.WithCompliance("pdf15"),
pdf.WithProducer("my-report-app"),
)
// HTML: single file, images inlined as base64, CSS prefix (avoids style clashes)
html.New(
html.WithSaveAsSingleFile(true),
html.WithExportImagesAsBase64(true),
html.WithCellCssPrefix("tbl_"),
)
// CSV: custom separator and encoding
// (the separator is a byte, and the encoding is a name — matched case- and
// punctuation-insensitively, so "UTF-8", "utf8" and "UTF8" are one name)
csv.New(
csv.WithSeparator(';'),
csv.WithEncoding("UTF-8"),
)
// Image: pick the type (the only switch the image package currently exposes)
image.New(image.WithImageType("png")) // or "jpg" / "svg" / "gif" / "tif" / …
提示:對於 CSV、HTML、image 等單檔輸出,引擎預設僅匯出它認為「活動」的工作表。若要控制範圍,請使用該格式本身的選項,例如
html.WithExportActiveWorksheetOnly(true)(僅匯出活動工作表?)、html.WithShowAllSheets(true)或csv.WithExportAllSheets(true)。像素級的影像品質、精確選擇要渲染的工作表以及其他深層控制仍然存在於引擎層,但目前的image套件僅公開WithImageType開關——若需要更多功能,請直接使用底層綁定;工具組會隨著時間持續加入更多選項。
E. 目錄批次轉換
日常的「將這個資料夾中的 Excel 轉換為 PDF」工作,透過副檔名推斷即可變得非常簡短:
func convertAll(inputDir, outputDir string) error {
if err := os.MkdirAll(outputDir, 0o755); err != nil {
return err
}
return filepath.Walk(inputDir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
return err
}
ext := strings.ToLower(filepath.Ext(path))
if ext != ".xlsx" && ext != ".xls" && ext != ".xlsm" && ext != ".csv" {
return nil
}
out := filepath.Join(outputDir, strings.TrimSuffix(filepath.Base(path), ext)+".pdf")
if err := convert(path, out); err != nil { // reuse the convert from section 2
return fmt.Errorf("convert %s: %w", path, err)
}
fmt.Printf("done: %s -> %s\n", path, out)
return nil
})
}
F. 分類錯誤
轉換器錯誤屬於可分類的哨兵錯誤;將它們與 errors.Is 結合使用以實現精確處理:
err := convert("in.xlsx", "out.xyz")
switch {
case errors.Is(err, toolkiterrors.ErrUnsupportedFormat):
log.Println("this extension has no registered output format")
case errors.Is(err, os.ErrNotExist):
log.Println("the input file does not exist")
default:
log.Printf("conversion failed: %v", err)
}
formats.List() 會返回目前已註冊的所有擴充功能(已排序、具備併發安全性)——對於產生「支援的格式」清單或錯誤提示非常方便。
5. 支援的格式概覽 (預設註冊 32 種)
| 系列 | 輸出副檔名 | 調整套件 |
|---|---|---|
| Excel | xlsx xlsm xltx xltm xls xlsb | saveoptions/ooxml, xls, xlsb |
| OpenDocument | ods xml dif dbf | saveoptions/ods, xml, dif, dbf |
| 文字 / 資料 | csv txt tsv json sql | saveoptions/csv, txt, json, sqlScript |
| 文件 / 版面 | pdf docx pptx xps pcl epub | saveoptions/pdf, docx, pptx, xps, pcl, ebook |
| 網頁 | html md | saveoptions/html, markdown |
| 影像 | png jpg jpeg gif bmp svg emf tif tiff | saveoptions/image |
為了保持二進位檔精簡,僅匯入您使用的子套件(例如 pdf);為了方便或通用分派,可使用空白匯入 …/register。匯入子套件會觸發其註冊;註冊表查詢不區分大小寫;未註冊的副檔名會回傳 nil(不是錯誤),由呼叫端決定備援行為。
6. 最佳實踐與注意事項
- 單一入口點 — 不要重新發明它。 File-to-file 使用
Convert(FilePathSource, formats.Get(ext)/constructor, FilePathSink);僅在需要位元組或串流時才切換 sink。不要自行手寫os.Open → ReadAll → … → os.WriteFile;source/sink 會管理資源並為您建立父目錄。 - 併發與授權。 底層引擎是原生的:不要在同一個進程的多個 goroutine 之間共享同一個
SaveOption/workbook 物件;大量工作時請順序處理檔案或在多個進程間平行化。評估版會限制載入次數(每個進程大約一百次NewWorkbook_Stream載入)——對於大型基準測試,請重新啟動進程以重置計數。 - 一次讀取輸入,然後重複使用。 若要從單一輸入產生多種格式,先使用
os.ReadFile讀入為[]byte,然後使用BytesSource反覆轉換,避免重複讀取磁碟和重新載入。 - 串流會被緩衝。
NewReaderSource在首次存取時會緩衝,因此適用於一次性的輸入,如 HTTP 請求主體,而不適合真正的超大型檔案串流(對於此類情況,請使用直接指向磁碟的FilePathSource)。 - 了解誰決定輸出佈局。
Convert為「一個輸入 → 一個輸出檔案」。如果需要 每個工作表一個檔案 或 zip,應使用manipulator.Split搭配FolderSink/ZipSink—— 不要強行透過Convert來實現。
