To export data from C++ to a spreadsheet, you can follow these steps:
- Include the necessary libraries:
TEXT/X-C++SRC
1#include <iostream>
2#include <fstream>
3#include <string>
4#include <vector>
- Open the spreadsheet file for writing:
TEXT/X-C++SRC
1std::ofstream outputFile("data.csv");
- Check if the file was opened successfully:
TEXT/X-C++SRC
1if (!outputFile) {
2 std::cout << "Failed to open data.csv" << std::endl;
3 return 1;
4}
- Create a vector to store the data:
TEXT/X-C++SRC
1std::vector<std::vector<std::string>> data = {
2 {"Name", "Age", "City"},
3 {"John Smith", "25", "New York"},
4 {"Jane Doe", "30", "San Francisco"},
5 {"Alice Johnson", "35", "Chicago"}
6};
- Write the data to the spreadsheet:
TEXT/X-C++SRC
1for (const auto& row : data) {
2 for (const auto& cell : row) {
3 outputFile << cell << ",";
4 }
5 outputFile << std::endl;
6}
- Close the file:
TEXT/X-C++SRC
1outputFile.close();
By following these steps, you can export data from C++ to a spreadsheet. The data is written to a CSV (Comma-Separated Values) file, which can be opened by popular spreadsheet applications like Microsoft Excel or Google Sheets.
xxxxxxxxxx
38
}
int main() {
// Open the spreadsheet file for writing
std::ofstream outputFile("data.csv");
// Check if the file was opened successfully
if (!outputFile) {
std::cout << "Failed to open data.csv" << std::endl;
return 1;
}
// Create a vector to store the data
std::vector<std::vector<std::string>> data = {
{"Name", "Age", "City"},
{"John Smith", "25", "New York"},
{"Jane Doe", "30", "San Francisco"},
{"Alice Johnson", "35", "Chicago"}
};
// Write the data to the spreadsheet
for (const auto& row : data) {
for (const auto& cell : row) {
outputFile << cell << ",";
}
outputFile << std::endl;
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment