In order to write data to a spreadsheet in C++, you can follow these steps:
Include the necessary header files:
#include <iostream>and#include <fstream>.Define a function
writeDataToSpreadsheetthat takes the filename of the spreadsheet and the data to be written as input.
TEXT/X-C++SRC
1void writeDataToSpreadsheet(const std::string& filename, const std::vector<std::vector<std::string>>& data) {
2 // Code to write data
3}- Inside the
writeDataToSpreadsheetfunction, open the spreadsheet file using anofstreamobject.
TEXT/X-C++SRC
1std::ofstream file(filename);- Check if the file was successfully opened, and handle the error if it fails.
TEXT/X-C++SRC
1if (!file.is_open()) {
2 std::cout << "Failed to open file" << std::endl;
3 return;
4}- Iterate over the
datavector, which contains the rows of the spreadsheet.
TEXT/X-C++SRC
1for (const auto& row : data) {
2 // Code to write row
3}- Inside the row loop, iterate over the cells of each row and write them to the file separated by commas.
TEXT/X-C++SRC
1for (const auto& cell : row) {
2 file << cell << ",";
3}
4file << std::endl;- Close the spreadsheet file.
TEXT/X-C++SRC
1file.close();- In the
mainfunction or wherever you want to use thewriteDataToSpreadsheetfunction, provide the filename and data to be written.
TEXT/X-C++SRC
1std::vector<std::vector<std::string>> data = { {"John", "Doe", "john.doe@example.com"}, {"Jane", "Smith", "jane.smith@example.com"} };
2std::string filename = "data.csv";
3
4writeDataToSpreadsheet(filename, data);- Finally, compile and run the program. The data will be written to the specified spreadsheet file.
TEXT/X-C++SRC
1int main() {
2 // Code to call writeDataToSpreadsheet
3 return 0;
4}By following these steps, you will be able to write data to a spreadsheet in C++. It's important to ensure that the file is successfully opened before writing, and handle any errors that may occur.
xxxxxxxxxx31
}void writeDataToSpreadsheet(const std::string& filename, const std::vector<std::vector<std::string>>& data) { std::ofstream file(filename); if (!file.is_open()) { std::cout << "Failed to open file" << std::endl; return; } for (const auto& row : data) { for (const auto& cell : row) { file << cell << ","; } file << std::endl; } file.close();}int main() { std::vector<std::vector<std::string>> data = { {"John", "Doe", "john.doe@example.com"}, {"Jane", "Smith", "jane.smith@example.com"} }; std::string filename = "data.csv"; writeDataToSpreadsheet(filename, data); std::cout << "Data written to spreadsheet: " << filename << std::endl;OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


