How can I export values from a QTableWidget
to .csv file or Excel file?
The program should collect values of three variables from a PLC. This PLC belongs to my company and have functions to do this collect.
Inserting items to QTableWidget
.cpp:
void MainWindow::on_pushInsert_clicked()
{
/*
the program already is connected to plc,
so I just have to choose the address inside of the plc.
*/
WORD wAddress = 50001;
WORD value1 = 0;
WORD value2 = 0;
WORD value3 = 0;
CollectVariables(wAddress,wValue);
int ID = 0;
string Name = "";
int Age = 0;
QTableWidget *table = ui->tableWidget;
for(i=0;i<10; i++) {
//id
CollectVariables(wAddress+i, value1);
table->setItem(i, 0, new QTableWidgetItem(value1));
//name
CollectVariables(wAddress+10+i, value2);
table->setItem(i, 1, new QTableWidgetItem(value2));
//age
CollectVariables(wAddress+20+i, value3);
table->setItem(i, 2, new QTableWidgetItem(value3));
tabela->selectRow(i);
}
}
The way I used to "export" QTableWidget
to .csv file (I can't export do excel) was to store the value of each space on the table to an array while inserting items to the table.
QFile
was used to create the .csv file and QTextStream
to insert values on it.
To improve the code I created a button to select the directory where this .csv file should be save.
Select Directory .cpp:
void MainWindow::on_pushSelectDir_clicked()
{
QFileDialog directory;
ui->lineEditDir->setText(directory.getSaveFileName(this,"Choose an directory"));
dir_name = ui->lineEditDir->text();
}
Create .csv file .cpp:
void MainWindow::on_pushExportCSV_clicked()
{
QFile data(dir_name+".csv");
if (data.open(QFile::WriteOnly | QIODevice::Append)) {
}
QTextStream output(&data);
output <<"ID"<<","<<"Name"<<","<<"Age"<< '\n';
for(i=0;i<10; i++) {
output << ID[i] <<","<< Name[i] <<","<< Age[i] << '\n';
}
data.close();
}