c++ reading excel file containing data and graph - c++

I am writing a program to read a excel file using c++. i need only the two columns of the file and the excel file just dont contain fields...it also contains graphs. there are 10 columns and the two columns i need are the first and 7th. converting into CSV didnt work. Any suggestions plz.
Thank you.

You need to save the file as CSV and then read in the CSV file using fopen. You also need to start doing your homework on your own and not asking people on the internet for help.

Excel can be driven programatically through its COM interface. Here is some code:
#include <windows.h>
#include <iostream>
#import "C:\Program Files\Common Files\Microsoft Shared\OFFICE11\MSO.DLL" rename( "RGB", "MSORGB" ), rename( "DocumentProperties", "MSODocProps" )
#import "C:\Program Files\Common Files\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB" rename ( "Application", "VBApplication" )
namespace Excel
{
using namespace Office;
using namespace VBIDE;
}
#import "C:\Program Files\Microsoft Office\OFFICE11\Excel.EXE" \
rename( "RGB", "RGB_" ), \
rename( "CopyFile", "CopyFile_" ), \
rename( "DialogBox", "DialogBox_" ), \
rename( "ReplaceText", "ReplaceText_" )
int main(int argc, char* argv[])
{
::CoInitialize( NULL );
try
{
Excel::_ApplicationPtr excel( "Excel.Application" );
Excel::WorkbooksPtr wbs = excel->Workbooks;
Excel::_WorkbookPtr wb = wbs->Open( _bstr_t( "c:\\temp\\test.xls" ) );
Excel::_WorksheetPtr sheet = wb->Sheets->GetItem( 1 ); // First sheet
Excel::RangePtr range = sheet->Cells->GetItem( 1, 1 ); // Row, column
_variant_t value = range->Value;
}
catch( _com_error& e )
{
std::cerr << "0x" << std::hex << e.Error() << std::endl;
}
catch( ... )
{
std::cerr << "Unexpected error" << std::endl;
}
::CoUninitialize();
return 0;
}
This code gets the value in cell A1 in a spreadsheet loaded from disc. You should be able to go from here to reading your two columns of data.

Related

how to handle excel files using C++?

I'm new to C++, And I want to enter values into an excel spreadsheet using C++, I know we can handle files using fstream but how to get a specific column or row using this method.
If you want to persist in using C++ (despite the comments above), this sample will give you an idea of the coding work needed to use C++ to automate the Excel application (as you might do in VBA or C#) rather than manipulate the file using a known file format (using a third-party library). The sample opens an existing worksheet in the background, adds 1 to the value in cell A1 on Sheet1, and then saves it.
Whether this is a suitable or efficient solution for your case will depend on what exactly you are trying to do with the files.
NB. Only works with the MS Visual Studio compiler.
The hard-coded paths to the import libraries may be different on your computer, and may depend on your Excel version.
//Import all the type libraries
#import "C:\Program Files\Microsoft Office\Root\VFS\ProgramFilesCommonX86\Microsoft Shared\OFFICE16\MSO.dll" \
rename("RGB","RGB_mso") rename("DocumentProperties","DocumentProperties_mso")
using namespace Office;
#import "C:\Program Files\Microsoft Office\root\vfs\ProgramFilesCommonX86\Microsoft Shared\VBA\VBA6\VBE6EXT.OLB"
using namespace VBIDE;
#import "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE" \
rename( "DialogBox", "ExcelDialogBox" ) \
rename( "RGB", "ExcelRGB" ) \
rename( "CopyFile", "ExcelCopyFile" ) \
rename( "ReplaceText", "ExcelReplaceText" ) \
exclude( "IFont", "IPicture" )
#include <iostream>
using namespace std;
int main()
{
HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED);
Excel::_ApplicationPtr pXL;
if (FAILED(pXL.CreateInstance("Excel.Application")))
{
cout << "Could not create instance of Excel" << endl;
return 1;
}
try
{
//Uncomment this to see what is going on during each step
//pXL->Visible = true;
Excel::_WorkbookPtr pWb = pXL->Workbooks->Open(L"c:\\temp\\testbook.xlsx");
//Gets number from cell A1 in Sheet1 and increments
Excel::_WorksheetPtr pSheet = pWb->Worksheets->Item[L"Sheet1"];
Excel::RangePtr pRng = pSheet->Cells;
_variant_t val = pRng->Item[1][1];
double dVal{ val };
pRng->Item[1][1] = ++dVal;
pWb->Save();
pWb->Close();
}
catch (_com_error ce)
{
cout << "Something went wrong" << endl;
_bstr_t bstrDesc = ce.Description();
if( ! bstrDesc )
{
cout << " Unknown Error" << endl;
}
else
{
cout << " Error text: " << bstrDesc << endl;
}
}
pXL->Quit();
}
EDIT: In answer to the unspoken question why is it Excel::_ApplicationPtr, Excel::_WorkbookPtr etc, but for a Range it is Excel::RangePtr (no _)? Absolutely no idea.
C++ is probably no the best choice to use if you want to manipulate .xlsx files. You would be better off either using macros in Excel using VBA, or you can write an Excel plugin using VSTO. If you really need to stick with C++, consider if you really need native Excel format. Maybe just .csv file be sufficient.
OpenXLSX is a great library for reading and writing excel sheets using C++. Its API documentation is not in the Github repo. It can be found here. The examples in the repo are quite extensive and detailed. Build instructions are also straightforward.
I have tried it on Linux and Windows (with MinGW). It works great and has the same behavior on both OSs.

fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory

I'm working on a project due in 2 days, and for the past 2 days, I've just been searching for a way to get this to work. I'm fairly new to C++, and our Class project requires us using C++ to make 5 games, and have them export to a MySQL database for a high scores table.
The MySQL database is no problem at all. My only problem is getting C++ to connect to the MySQL database.
So here's some more info incase someone can help me.
I'm using Visual Studio 2010 and 2012 for this. (As in I have VS 2012, while my school has 2010, so I don't know if there is any compatability differences for this, but I also have VS2010).
I've been searching the web for 5 hours or more about these kind of things, like why my "#include " statement won't work, and I've learned about going into the project properties and adding different include libraries. Usually after surfing for a while, I can figure out where I went wrong, but here I've just hit a dead end, as the only help I can find with this says to include boost, which I have done, but I'm completely stumped to this point. My Friends I'm doing this class project with are getting impatient, as this is the last thing we have left to do.
So here's the things I think I should include.
My Includes for both test programs I am doing (both are the exact same)
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\include
C:\Program Files\MySQL\MySQL Server 5.6\include
My Linker->"Additional Library Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
C:\Program Files\MySQL\MySQL Connector C++ 1.1.3\lib\opt
C:\Program Files\MySQL\MySQL Server 5.6\lib
My code for both programs I am trying to run.
This one is the one I was testing on Visual Studio 2012
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
#include <stdlib.h>
#include <Windows.h>
#include <mysql.h>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#define host "localhost"
#define username "username"
#define password "password"
#define database "db_test"
int main()
{
MYSQL* conn;
conn = mysql_init( NULL );
if( conn )
{
mysql_real_connect( conn, host, username, password, database, 0, NULL, 0 );
}
MYSQL_RES* res_set;
MYSQL_ROW row;
unsigned int i;
mysql_query( conn, "SELECT * FROM tbl_clients WHERE id = 1" );
res_set = mysql_store_result( conn );
unsigned int numrows = mysql_num_rows( res_set );
if( numrows )
{
row = mysql_fetch_row( res_set );
if( row != NULL )
{
cout << "Client ID : " << row[0] << endl;
cout << "Client Name: " << row[1] << endl;
}
}
if( res_set )
{
mysql_free_result( res_set );
}
if( conn )
{
mysql_close( conn );
}
return 0;
}
This is the Code I'm trying to compile on Visual Studio 2010
#include <stdio.h>
#define W32_LEAN_AND_MEAN
#include <winsock2.h>
#include "mysql.h"
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <iostream>
// change these to suit your setup
#define TABLE_OF_INTEREST "highscores"
#define SERVER_NAME "127.0.0.1"
#define DB_USER "root"
#define DB_USERPASS "root"
#define DB_NAME "test"
// prototypes
void showTables(MYSQL*);
void showContents(MYSQL*,const char*);
using namespace std;
int main(int argc, char* argv[])
{
MYSQL *hnd=NULL; // mysql connection handle
const char *sinf=NULL; // mysql server information
hnd = mysql_init(NULL);
if (NULL == mysql_real_connect(hnd,SERVER_NAME,DB_USER,DB_USERPASS,DB_NAME,0,NULL,0))
{
fprintf(stderr,"Problem encountered connecting to the %s database on %s.\n",DB_NAME,SERVER_NAME);
}
else
{
fprintf(stdout,"Connected to the %s database on %s as user '%s'.\n",DB_NAME,SERVER_NAME,DB_USER);
sinf = mysql_get_server_info(hnd);
if (sinf != NULL)
{
fprintf(stdout,"Got server information: '%s'\n",sinf);
showTables(hnd);
showContents(hnd,TABLE_OF_INTEREST);
}
else
{
fprintf(stderr,"Failed to retrieve the server information string.\n");
}
mysql_close(hnd);
}
return 0;
}
void showTables(MYSQL *handle)
{
MYSQL_RES *result=NULL; // result of asking the database for a listing of its tables
MYSQL_ROW row; // one row from the result set
result = mysql_list_tables(handle,NULL);
row = mysql_fetch_row(result);
fprintf(stdout,"Tables found:\n\n");
while (row)
{
fprintf(stdout,"\t%s\n",row[0]);
row = mysql_fetch_row(result);
}
mysql_free_result(result);
fprintf(stdout,"\nEnd of tables\n");
return;
}
void showContents
(
MYSQL *handle,
const char *tbl
)
{
MYSQL_RES *res=NULL; // result of querying for all rows in table
MYSQL_ROW row; // one row returned
char sql[1024], // sql statement used to get all rows
commastr[2]; // to put commas in the output
int i,numf=0; // number of fields returned from the query
sprintf(sql,"select * from %s",tbl);
fprintf(stdout,"Using sql statement: '%s' to extract all rows from the specified table.\n",sql);
if (!mysql_query(handle,sql))
{
res = mysql_use_result(handle);
if (res)
{
numf = mysql_num_fields(res);
row = mysql_fetch_row(res);
fprintf(stdout,"Rows returned:\n\n");
while (row)
{
commastr[0]=commastr[1]=(char)NULL;
for (i=0;i<numf;i++)
{
if (row == NULL)
{
fprintf(stdout,"%sNULL",commastr);
}
else
{
fprintf(stdout,"%s%s",commastr,row);
}
commastr[0]=',';
}
fprintf(stdout,"\n");
row = mysql_fetch_row(res);
}
fprintf(stdout,"\nEnd of rows\n");
mysql_free_result(res);
}
else
{
fprintf(stderr,"Failed to use the result acquired!\n");
}
}
else
{
fprintf(stderr,"Failed to execute query. Ensure table is valid!\n");
}
return;
}
Now both of these give me this error
1>c:\program files\mysql\mysql connector c++ 1.1.3\include\cppconn\connection.h(31): fatal error C1083: Cannot open include file: 'boost/variant.hpp': No such file or directory
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Please help! Note: I'm only trying to connect to the database with success so I can run different queries and whatnot. These programs are just tests that I've copied from elsewhere.
Thanks!!
I think
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0\boost
needs to be
"Additional Include Directories"
C:\Users\Damian\Desktop\boost_1_53_0\boost_1_53_0

File I/O using COCOS2D-X

I'm trying to load up a Comma Separated file called POSDATA.GAMEDATA. I've looked up several places on the internet and it turns out I need to do some tweaking and / or a different class.
I tried using ifstream. However, it cannot open the file. Xcode 4.3.2 cannot seem to find my POSDATA.GAMEDATA file. I also tried to make the file using ofstream but when I use open() in both cases, the file is not opened.
My code is something like this:
using namespace std;
void FileLoader::loadFile( string p_WhichFile ) {
// Local Variables
string thisLine;
// Open POSDATA.GAMEDATA
ifstream dataStream;
dataStream.open( p_WhichFile.c_str( ) );
// Check if file is opened
if ( !dataStream ) {
cerr << "[ ERROR ] Cannot load file:" << p_WhichFile.c_str( ) << endl;
exit( 1 );
}
// Get lines of strings
while ( getline( dataStream, thisLine ) ) {
fileContents.push_back( thisLine ); // fileContents is a vector< string > object
}
dataStream.close( );
cout << "[ NOTICE ] Finished reading file" << p_WhichFile << endl;
}
I've seen CCFileUtils but I can't seem to get how to use it.
EDIT: I've tried supplying the absolute path ( /Users/LanceGray/Documents/LanceDev/COCOS2DX/cocos2dx/TestGame/Data/POSDATA.GAMEDATA ) and it worked. However, I cannot do this since the game is supposed to be used in iOS devices and Android, so the path is not always the same on each device. Any help will be grealy appreciated.
I got working by using CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( "POSDATA.GAMEDATA" );
A more detailed explanation:
Add the files that you need in the Project by going to the Project Tree on the left and Right-click -> Add Files. What I did was I added a new folder called Data on the same level as the Resources and Classes folders and placed my POSDATA.GAMEDATA file there. In Xcode, I added a new group and added that file in that group.
Then I used ifstream to open the file.
When opening the file, use CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( ) to get the absolute path of the file. Supply the file name on the fullPathFromRelativePath( ) as argument.
Try to run it and it should work fine.
A small example:
// FileReader.h
#include "cocos2d.h"
using namespace std;
using namespace cocos2d;
class FileReader {
private:
vector< string > mFileContents;
public:
FileReader( string pFileName, char pMode = 'r' );
};
// FileReader.cpp
#include "FileReader.h"
#include <fstream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
FileReader::FileReader( string pFileName, char pMode ) {
// Create input file stream
ifstream inputStream;
string thisLine;
// Open file
inputStream.open( CCFileUtils( )::sharedFileUtils( ) -> fullPathFromRelativePath( pFileName ).c_str( ) );
// Check if it is open
if ( !inputStream.is_open( ) ) {
cerr << "[ ERROR ] Cannot open file: " << pFileName.c_str( ) << endl;
exit( 1 );
}
while ( getline( inputStream, thisLine ) ) {
// Put all lines in vector
mFileContents.push_back( thisLine );
}
inputStream.close( );
cout << "[ NOTICE ] Finished opening file: " << pFileName.c_str( ) << endl;
}
This class will load a file with the name pFileName and place it on its member variable mFileContents. ( Note that it should have a public get function like vector< string > getFileContents( ) to access the mFileContents because it is private )
EDIT: The above sample will work on iOS, however, it won't on Android devices. So to fix this, instead of using ifstream, use CCFileUtils::sharedUtils( ) -> getFileData( ) instead. In conjunction with CCFileUtils::sharedUtils( ) -> fullPathFromRelativePath( ), we will be able to achieve our goal of reading a plain text file that works on both iOS and Android.
The FileReader class would then be like this:
// FileReader.cpp
#include "FileReader.h"
#include <fstream>
#include "cocos2d.h"
using namespace cocos2d;
using namespace std;
FileReader::FileReader( string pFileName, char pMode ) {
// Initialize variables needed
unsigned long fileSize = 0;
unsigned char * fileContents = NULL;
string thisLine, result, fullPath, contents;
// Get absolute path of file
fullPath = CCFileUtils::sharedFileUtils( ) -> fullPathFromRelativePath( pFileName.c_str( ) );
// Get data of file
fileContents = CCFileUtils::sharedFileUtils( ) -> getFileData( fullPath.c_str( ) , "r", &fileSize );
contents.append( ( char * ) fileContents );
// Create a string stream so that we can use getline( ) on it
istringstream fileStringStream( contents );
// Get file contents line by line
while ( getline( fileStringStream, thisLine ) ) {
// Put all lines in vector
mFileContents.push_back( thisLine );
}
// After this, mFileContents will have an extra entry and will have the value '\x04'.
// We should remove this by popping it out the vector.
mFileContents.pop_back( );
// Delete buffer created by fileContents. This part is required.
if ( fileContents ) {
delete[ ] fileContents;
fileContents = NULL;
}
// For testing purposes
cout << "[ NOTICE ] Finished opening file: " << pFileName.c_str( ) << endl;
}
// For versions less than v2.0.1
// The version I am using is 0.12.0
unsigned long fileSize = 0;
char* pBuffer = CCFileUltils::getFileData("relative_path","r",&fileSize);
CCLOG("Data is %s",pBuffer);
You can reference from Cocos's wiki
Read/write file in cocos2d

Using fprintf at a C++ code

I have an odd problem. When I try to compile the code below, it works without a failure as expected:
#include <iostream>
#include <Windows.h>
int main(){
FILE *f = fopen("trystl.geo","w");
fprintf(f,"Merge \"trystl.stl\";");
fprintf(f,"\n");
fprintf(f,"Surface Loop(2) = {1};");
fprintf(f,"\n");
fprintf(f,"Volume(3) = {2};");
fclose(f);
return 0;
}
But when I try to connect this program to a button with FLTK user interface, it gives me an assertion runtime error. The segment of my code:
void UserInterface::cb_m_BtnSTLToGEOConverter_i(Fl_Button*, void*){
//OnSTLToGEOConvert();
FILE *f = fopen("trystl.geo","w");
fprintf(f,"Merge \"trystl.stl\";");
fprintf(f,"\n");
fprintf(f,"Surface Loop(2) = {1};");
fprintf(f,"\n");
fprintf(f,"Volume(3) = {2};");
fclose(f);
}
void UserInterface::cb_m_BtnSTLToGEOConverter(Fl_Button* o, void* v){
((UserInterface*)(o->parent()->parent()->parent()->parent()->parent()->parent()->parent()->user_data()))->cb_m_BtnSTLToGEOConverter_i(o,v);
}
When the user presses the button, I want the program to create a file called trystl.geo and perform the operations shown. But when compile and open the program and click the button, it says:
Debug Assertion Failed!
Program: *.......\src\fprintf.c Line 55:
Expression: (str! NULL)
abort retry or ignore...
I'm using Visual Studio 2010.
The error is simple: Line 55 in fprintf.c in VC++ is _VALIDATE_RETURN( (str != NULL), EINVAL, -1); and str is the FILE* parameter (I've seen better named variables though).
For the curious (I was) _VALIDATE_RETURN is defined as follows:
#define _VALIDATE_RETURN( expr, errorcode, retexpr ) \
{ \
int _Expr_val=!!(expr); \
_ASSERT_EXPR( ( _Expr_val ), _CRT_WIDE(#expr) ); \
if ( !( _Expr_val ) ) \
{ \
errno = errorcode; \
_INVALID_PARAMETER(_CRT_WIDE(#expr) ); \
return ( retexpr ); \
} \
}
So better check if your fopen() call succeeds before trying to write to a nonexistant filedescriptor.
OK I found the solution. The only problem is that if you don't type in the whole path in the program, the file doesn't get opened. I replaced
FILE *f = fopen("trystl.geo","w");
with
FILE *f = fopen("c:/Users/anypath/trystl.geo","w");
it works!
Thank you for all your help!

how connect mysql using c++

Editor's Note: Original Text:
how connect mysql using c++
#include <iostream>
#include <fstream>
#include <string>
#include "/usr/local/mysql5/include/mysql.h"
using namespace std;
int main() {
MYSQL *mysql;
MYSQL_RES *result;
MYSQL_ROW row;
string server = "192.168.1.92";
string username = "useradmin";
string password = "useradmin";
string database = "market";
int port = 3306;
mysql = mysql_init(0);
if ( !mysql_real_connect( mysql, server.c_str(), username.c_str(), password.c_str(), database.c_str(), port, NULL, 0 ) ) {
fprintf( stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
if ( !mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {
fprintf(stderr, "%s\n", mysql_error( mysql ) );
return 0;
}
result = mysql_use_result( mysql );
ofstream SaveFile("/tmp/dict.txt");
while ( ( row = mysql_fetch_row( result ) ) != NULL ) {
//SaveFile << fprintf( stdout, "%s\t%d", row[0], $row[1] ) << endl;
cout << row[0] << endl;
}
mysql_free_result( result );
mysql_close( mysql );
SaveFile.close();
return 1;
}
undefined reference to mysql_init'
undefined reference tomysql_real_connect'
...
Editor's Note: A translation was attempted:
I'm using Eclipse, and I get compilation errors using mysql.h. How do I link to mysql?
#include "mysql.h"
Editor's Note: English questions are required on Stack Overflow. Please do your best at translating your question to English as needed, even if you have to use an automatic translation service like Google Translate.
Editor's Note: Original Text:
信息太少了, 把编译器错误贴出来看看.
可能因为:
mysql.h不在配置的include目录中.
Mysql库文件不在link列表里面
头文件与二进制库文件不配套
Editor's Note: A translation was attempted:
There's too little information in your question. Post the actual compiler error into your question.
That being said, the error may be caused by:
Mysql.h is not in the configuration or in the include directory.
MySql database file is not in the linker's path.
Header and library files are not consistent with each other.
An issue in the sample is that mysql_query returns 0 on SUCCESS – so it always thinks an error occurred on success.
Change it to:
if ( mysql_query( mysql, "SELECT text, prequency FROM ma_dict" ) ) {