前言:
一年前在学数据库的时候,有个想法,就是怎么用代码来读取excel的数据;为此,我曾请教Boss Liu,Boss Liu指点说OpenSource里有我要的东西。由于一些小事情,耽搁了,结果这个想法就over了;没想到,现在我需要用上;既然如此,那我得好好学学。在此我要感谢Boss Liu的指导,否则对于这问题,我估计现在也不知道怎么解决;
正题:
BasicExcel
1.设计者:新加坡人Yap Chun Wei;
2.基本的功能(对excel里的sheet进行的操作):
1)Read and write number (integers, real numbers) and strings (ANSI, UTF16)
2)Add worksheets
3)Rename worksheets
4)Delete worksheets
5)Get the name of a worksheet
3.优点:
1)采用com方式实现,访问速度快,api接口也比较简单
2)可以跨平台使用
4.一些操作(读取操作)的具体实现
1)prepare:
下载BasicExcel;说明:该包里面有四个文件,由于演示程序不是没用MFC,所以只需要将BasicExcel.hpp与BasicExcel.cpp放在你建的工程下面,或者可以将四个文件都放在你自己的类库中,然后导入;
使用的excel的名字:classification.data.xls
sheet的名字:analysis.data
2)show:
#include "BasicExcel.hpp"
// Load a workbook with one sheet, display its contents
int main(int argc, char* argv[])
{
BasicExcel e;
// load excel
e.Load("classification.data.xls");
BasicExcelWorksheet* sheet = e.GetWorksheet("analysis.data");
if (sheet){
size_t maxRows = sheet->GetTotalRows();
size_t maxCols = sheet->GetTotalCols();
cout << "Dimension of " << sheet->GetAnsiSheetName() <<
" (" << maxRows << ", " << maxCols << ")" << endl;
for (size_t r = 0; r < maxRows; ++r){
printf("%10d", r+1);
for (size_t c = 0; c < maxCols; ++c){
BasicExcelCell* cell = sheet->Cell(r,c);
switch (cell->Type())
{
case BasicExcelCell::UNDEFINED:
printf(" ");
break;
case BasicExcelCell::INT:
printf("%10d", cell->GetInteger());
break;
case BasicExcelCell::DOUBLE:
printf("%10.6lf", cell->GetDouble());
break;
case BasicExcelCell::STRING:
printf("%10s", cell->GetString());
break;
case BasicExcelCell::WSTRING:
wprintf(L"%10s", cell->GetWString());
break;
}
}
cout << endl;
}
}else{
printf("cannot read this sheet!\n");
}
cout << endl;
return 0;
}
#include "BasicExcel.hpp"
// Create a new workbook and write some contents.
int main(int argc, char* argv[])
{
BasicExcel e;
// create a workbook
e.New();
// create a sheet
BasicExcelWorksheet* sheet = e.AddWorksheet("analysis.data");
// cell
BasicExcelCell* cell;
if (sheet){
size_t c;
// SetString
for (c = 0; c < 4; ++c){
cell = sheet->Cell(0, c);
cell->SetString("property");
// sheet->Cell(0,c)->SetInteger("property");
}
// SetInteger
for (c = 0; c < 4; ++c){
cell = sheet->Cell(1, c);
cell->SetInteger(c);
// sheet->Cell(1,c)->SetInteger(c);
}
// SetDouble
for (c = 0; c < 4; ++c){
cell = sheet->Cell(2, c);
double data = c / 2.0;
cell->SetDouble(data);
// sheet->Cell(2,c)->SetDouble(data);
}
}
// save to a excel
e.SaveAs("classification.data.xls");
return 0;
}
本文介绍了BasicExcel库的基本使用方法,包括如何加载和保存Excel文件、读取单元格内容及类型,以及创建新的工作簿和工作表并写入数据。
7万+

被折叠的 条评论
为什么被折叠?



