由于工作需要,要实现对Excel的读写功能,在网上找到了CSPReadSheet类来操作excel,关于CSpreadSheet的相关介绍可以参考:
英文:http://www.codeguru.com/cpp/data/mfc_database/microsoftexcel/article.php/c4307/CSpreadSheet.htm
中文:http://www.oschina.net/question/76782_12420
开始之前,需要先下载CSpreadSheet类文件。
链接:http://download.csdn.net/download/hao2001/3036187
2.编译成动态库(VS2005)
1).新建项目
选择MFC DLL,名称自定,点击确定。
点击下一步
使用默认,点击完成
创建成功
2).编辑项目
a.修改OperateExcel.h
打开CSpreadSheet.h文件,把需要的内容复制,修改为:
上图圈住的地方就是要修改的地方。
b.修改OperateExcel.cpp
把COperateExcelApp改为CSpreadSheet,如下图:
由于,CSpreadSheet不需要默认构造函数,所以中间那段都注释掉。
然后打开CSpreadSheet.cpp,除了头文件把所有内容都复制过来:
OK。
c.修改配置
到此为止,接下来该编译了,编译完成后,会生成.lib和.dll文件:
3).读写EXCEL
a.先创建一个win32控制台程序
b.将文件OperateExcel.h,Resource.h,stdafx.h,stdafx.cpp,OperateExcel.dll,OperateExcel.lib拷贝到新建项目的程序所在目录下
c.把OperateExcel.h,Resource.h,stdafx.h,stdafx.cpp手动添加到项目中
d.在新建项目的cpp文件中加入OperateExcel.h,stdafx.h头文件
e.在main函数中写入测试代码:
[cpp] view plain copy print?int main() { CSpreadSheet SS("Test.xls", "TestSheet"); CStringArray Rows; CStringArray sampleArray, testRow, Column; CString tempString; char alphabet = 'A'; SS.BeginTransaction(); for (int i = 1; i <= 5; i++) { sampleArray.RemoveAll(); for (int j = 1; j <= 5; j++) { tempString.Format("%c%d", alphabet++, i); sampleArray.Add(tempString); } alphabet = 'A'; if (i == 1) // Add header rows { SS.AddHeaders(sampleArray); } else // Add data rows { SS.AddRow(sampleArray); } } // Set up test row for appending, inserting and replacing for (int k = 1; k <= 5; k++) { testRow.Add("Test"); } SS.AddRow(testRow); // append test row to spreadsheet SS.AddRow(testRow, 2); // insert test row into second row of spreadsheet SS.AddRow(testRow, 4, true); // replace fourth row of spreadsheet with test row SS.Commit(); printf("Total number of rows = %d/n/n", SS.GetTotalRows()); return 0; } f.配置项目
注意:除了按照上面动态库的配置以外,新项目的输入项加入accessExcel.lib(当前目录)
编译成功后,运行会在项目的当前目录中生成一个Test.xls文件,并且有内容。
新闻热点
疑难解答