C++ 控制檯讀寫excel

小白study發表於2016-10-08

為求簡單方便,直接使用開源——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

相關文章