If you are working on a report class program, it may be necessary to export the content as an Excel file. I wrote a class before using MFC to export the data in the grid to an Excel file. After using the Qtsql module, I can easily apply this class rewrite to the QT program. The name of the class is called "Exportexcelobject". It's easy to use:
[CPP]
1. Declare an Object
–filename Excel file path
–sheetname Excel Worksheet (sheet) name
–tableview Qtableview pointers that need to be exported
Exportexcelobject obj (fileName, SheetName, TableView);
2. Define fields (columns) to the Excel sheet file
– The 1th parameter is a column of Qtableview
– the 2nd parameter is a column name in Excel sheet that should be listed
– the 3rd parameter is the type of the column, you can use char (x) (x Max 255), Int,datetime, and so on
Obj.addfield (1, TR ("name"), "char (60)");
Obj.addfield (2, tr ("ID"), "int");
Obj.addfield (3, TR ("Time"), "datetime");
3. The class has a specific signal for connecting a progress control that can show the progress of the export
Connect (&obj, SIGNAL (exportedrowcount (int)), ProgressBar, SLOT (setValue (int)));
4. Do the work
int retVal = Obj.export2excel ();
if (RetVal > 0)
{//done
}
Else
{//something wrong
}
So how does this class be implemented?
- Treat an Excel file as a database
If you use MS ODBC or ADO to treat Excel files as a database, then we just need to use this DSN connection string to create and connect to the Excel file:
[CPP]View Plaincopy
- QString DSN = QString ("Driver={microsoft Excel DRIVER (*.xls)};D sn="; Firstrowhasnames=1;; create_db=/"%1/";D bq=%2 ").
-
- Arg (Excelfilepath). Arg (Excelfilepath);
- Treat Excel's worksheet (sheet) as a database table
You can use the SQL statement "CREATE TABLE" to create a worksheet.
- Inserting data into a table
Insert the data using the SQL INSERT statement.
- Unicode support
Yes, both column names and data support Unicode.
I have written an example to illustrate this class (download). This program works correctly in WINXP/VISTA/7. This app does not need to have Excel installed on your PC because {Microsoft Excel Driver (*.xls)} starts with Windows 2000 and the system comes with its own support.
http://blog.csdn.net/superjoel/article/details/5321404
QT to export data from Qtableview to Excel files