C++ 控制台读写excel

为求简单方便,直接使用开源——CSpreadSheet.h文件在CodeProjectCodeGuru上都有,其实是这个文件有问题。这个头文件既包括了CSpreadSheet类的定义,还包括这个类的实现,这样所有包含这个头文件的类都有一份这个类的实现,链接的时候可能会出错了。只要工程中有两个以上的地方包含这个头文件就会出现错误。解决的办法很简单,建立一个CSpreadSheet.cpp文件,然后在这个文件的开头加上:

#include “stdafx.h”
#include “CSpreadSheet.h”

然后把CSpreadSheet.h文件中从”// Open spreadsheet for reading and writing”(含)到”#endif”(不含)之前的语句都剪切到CSpreadSheet.cpp中,也就是将类的声明和实现分离,再将CSpreadSheet.cpp文件加到工程中,这样就可以了。

 

注意在上述操作完成后,仍然会有可能出错——原因是使用了MFC库,因此在工程中要相应地进行设置,包括:

1、添加MFC类库支持——在stdafx.h文件中添加

#include <afxwin.h> 
#include <afxext.h>

2、设置工程的字符类型——VS默认是Unicode;

3、根据出错信息选择代码生成中的运行时库(至少我的这一步是要求作修改的)

 

Win32控制台程序中,使用MFC的方法

使用样例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
int  _tmain( int  argc, _TCHAR* argv[])
{
     // Create a new Excel spreadsheet, filename is test.xls, sheetname is TestSheet
     CSpreadSheet SS( "d:\\name1.xls" "Sheet1" , false );
 
     // read
     CStringArray sampleArray, testRow, Rows, Column;
     CString tempString;
     int  i = 0;
     for  (i = 1; i <= SS.GetTotalRows(); i++)
     {
         // Read row
         SS.ReadRow(Rows, i);
         for  ( int  j = 1; j <= Rows.GetSize(); j++)
         {
             if  (j != Rows.GetSize())
             {
                 printf ( "%s\t" , Rows.GetAt(j-1));
             }
             else
             {
                 printf ( "%s\n" , Rows.GetAt(j-1));
             }
         }
     }
 
     // print out total number of columns
     printf ( "\nTotal number of columns = %d\n\n" , SS.GetTotalColumns());
 
     // Read and print out contents of second column of spreadsheet
     SS.ReadColumn(Column, 2);
     for  (i = 0; i < Column.GetSize(); i++)
     {
         printf ( "Column 2 row %d: %s\n" , i+1, Column.GetAt(i));
     }
 
     // Read in and print out the cell value at column 3, row 3 of spreadsheet
     if  (SS.ReadCell(tempString, 3, 3))
     {
         printf ( "\nCell value at (3,3): %s\n" , tempString);
     }
     else
     {
         // print out error message if cell value cannot be read
         printf ( "Error: %s\n" , SS.GetLastError());
     }
 
     return  0;
}

 转载于http://www.cnblogs.com/bruce5/archive/2012/06/20/2556376.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值