ExcelをCSV、TSV、Txtに変換するC++による方法
ワークブックをテキストまたはCSV形式で保存
時々、複数のワークシートを含むワークブックをテキスト形式に変換または保存したい場合があります。テキスト形式(たとえば、TXT、TabDelim、CSVなど)の場合、デフォルトでMicrosoft ExcelおよびAspose.Cellsの両方はアクティブなワークシートの内容のみを保存します。
以下のコード例では、ワークブック全体をテキスト形式で保存する方法について説明しています。任意のMicrosoft ExcelまたはOpenOfficeスプレッドシートファイル(XLS、XLSX、XLSM、XLSB、ODSなど)を読み込み、任意の数のワークシートを含めることができます。
コードを実行すると、ワークブックのすべてのシートのデータがTXT形式に変換されます。
同じ例を修正して、ファイルをCSVに保存することもできます。デフォルトでは、TxtSaveOptions.GetSeparator()はカンマです。CSV形式に保存する場合は区切り文字を指定しないでください。
#include <iostream>
#include "Aspose.Cells.h"
#include "Aspose.Cells/TxtSaveOptions.h"
using namespace Aspose::Cells;
int main()
{
Aspose::Cells::Startup();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
// Source directory path
U16String srcDir(u"..\\Data\\01_SourceDirectory\\");
// Path of input Excel file
U16String inputFilePath = srcDir + u"book1.xls";
// Load your source workbook
Workbook workbook(inputFilePath);
// Text save options. You can use any type of separator
TxtSaveOptions opts;
opts.SetSeparator(u'\t');
opts.SetExportAllSheets(true);
// Save entire workbook data into file
U16String outputFilePath = srcDir + u"out.txt";
workbook.Save(outputFilePath, opts);
std::cout << "Workbook saved successfully as text file!" << std::endl;
Aspose::Cells::Cleanup();
}
カスタム区切り文字でテキストファイルを保存
テキストファイルには書式がないスプレッドシートデータが含まれます。ファイルは、データ間にいくつかのカスタマイズされた区切り記号があるプレーンテキストファイルの種類です。
#include <iostream>
#include "Aspose.Cells.h"
#include "Aspose.Cells/TxtSaveOptions.h"
using namespace Aspose::Cells;
int main()
{
Aspose::Cells::Startup();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C
// Source directory path
U16String srcDir(u"..\\Data\\01_SourceDirectory\\");
// Path of input excel file
U16String filePath = srcDir + u"Book1.xlsx";
// Create a Workbook object and opening the file from its path
Workbook workbook(filePath);
// Instantiate Text File's Save Options
TxtSaveOptions options;
// Specify the separator
options.SetSeparator(u';'); // Using U16String for the char
// Save the file with the options
workbook.Save(srcDir + u"output.csv", options);
std::cout << "File saved successfully!" << std::endl;
Aspose::Cells::Cleanup();
}