VC++读取,写入,查询 Excel文件

具体实现

 一、 操作类头文件

#include "CSpreadSheet.h"
下载地址:http://www.codeproject.com/KB/database/cspreadsheet.aspx

 二、 新建Excel文件,并写入默认数据

// 新建Excel文件名及路径,TestSheet为内部表名
CSpreadSheet SS("c://Test.xls", "TestSheet");
CStringArray sampleArray, testRow;
SS.BeginTransaction();

// 加入标题
sampleArray.RemoveAll();
sampleArray.Add("姓名");
sampleArray.Add("年龄");
SS.AddHeaders(sampleArray);

// 加入数据
CString strName[] = {"徐景周","徐志慧","郭徽","牛英俊","朱小鹏"};
CString strAge[] = {"27","23","28","27","26"};
for(int i = 0; i < sizeof(strName)/sizeof(CString); i++)
{
sampleArray.RemoveAll();
sampleArray.Add(strName[i]);
sampleArray.Add(strAge[i]);
SS.AddRow(sampleArray);
}
SS.Commit();


 三、 读取Excel文件数据

CSpreadSheet SS("c://Test.xls", "TestSheet");
CStringArray Rows, Column;

//清空列表框
m_AccessList.ResetContent();
for (int i = 1; i <= SS.GetTotalRows(); i++)
{
// 读取一行
SS.ReadRow(Rows, i);
CString strContents = "";
for (int j = 1; j <= Rows.GetSize(); j++)
{
if(j == 1)
strContents = Rows.GetAt(j-1);
else
strContents = strContents + " --> " + Rows.GetAt(j-1);
}
m_AccessList.AddString(strContents);
}


四、 对已存在Excel表格数据进行添加、插入、替换操作

// 初始化测试行数据,进行添加、插入及替换数据操作演示
for (int k = 1; k <= 2; k++)
{
testRow.Add("Test");
}

SS.AddRow(testRow); // 添加到尾部
SS.AddRow(testRow, 2); // 插入新行到第二行
SS.AddRow(testRow, 6, true); // 替换原第四行来新的内容
SS.AddCell("徐景周", 1,2); // 添加(不存在)或替换(存在)第二行,第一列单元格内容
SS.Commit();

五、 对已存在Excel表格数据进行行、列、单元格查询

void CExcelAccessDlg::OnQuery() 
{
CSpreadSheet SS("c://Test.xls", "TestSheet");
CStringArray Rows, Column;
CString tempString = "";
UpdateData();
if(m_strRow == "" && m_strColumn == "") // 查询为空
{
AfxMessageBox("行号、列号不能同时为空!");
return;
}
else if(m_strRow == "" && m_strColumn != "") // 查询指定列数据
{
int iColumn = atoi(m_strColumn);
int iCols = SS.GetTotalColumns();
if(iColumn > iCols) // 超出表范围查询时
{
CString str;
str.Format("表中总列数为: %d, ", iCols);
AfxMessageBox(str + " 查询列数大于Excel表中总列数,请重新输入!");
return;
}

// 读取一列数据,并按行读出
if(!SS.ReadColumn(Column, iColumn))
{
AfxMessageBox(SS.GetLastError());
return;
}

CString tmpStr;
for (int i = 0; i < Column.GetSize(); i++)
{
tmpStr.Format("行号: %d, 列号: %d ,内容: %s/n", i+1,iColumn,Column.GetAt(i));
tempString += tmpStr;
}

AfxMessageBox(tempString);
}
else if(m_strRow != "" && m_strColumn == "") // 查询指定行数数据
{
int iRow = atoi(m_strRow);
int iRows = SS.GetTotalRows();

if(iRow > iRows) // 超出表范围查询时
{
CString str;
str.Format("表中总行数为: %d, ", iRows);
AfxMessageBox(str + " 查询行数大于Excel表中总行数,请重新输入!");
return;
}

// 读取指定行数据
if(!SS.ReadRow(Rows, iRow))
{
AfxMessageBox(SS.GetLastError());
return;
}

CString tmpStr;
for (int i = 0; i < Rows.GetSize(); i++)
{
tmpStr.Format("行号: %d, 列号: %d ,内容: %s/n", iRow, i+1, Rows.GetAt(i));
tempString += tmpStr;
}

AfxMessageBox(tempString);
}
else if(m_strRow != "" && m_strColumn != "") // 查询指定单元格数据
{
int iRow = atoi(m_strRow), iColumn = atoi(m_strColumn);
int iRows = SS.GetTotalRows(), iCols = SS.GetTotalColumns();

if(iColumn > iCols) // 超出表范围查询时
{
CString str;
str.Format("表中总列数为: %d, ", iCols);
AfxMessageBox(str + " 查询列数大于Excel表中总列数,请重新输入!");
return;
}
else if(iRow > iRows)
{
CString str;
str.Format("表中总行数为: %d, ", iRows);
AfxMessageBox(str + " 查询行数大于Excel表中总行数,请重新输入!");
return;
}

// 读取指定行、列单元格数据
if(!SS.ReadCell(tempString, iColumn, iRow))
{
AfxMessageBox(SS.GetLastError());
return;
}

CString str;
str.Format("行号: %d, 列号: %d ,内容: %s", iRow,iColumn,tempString);
AfxMessageBox(str);
}

}


 六、 将存在的Excel转换另存为指定分隔的文本文件

// 将原Excel文件转换为用分号分隔的文本,并另存为同名文本文件
SS.Convert(";");
 七、删除Excel中表格
SS. DeleteSheet();            // 删除Excel文件中所有表格
SS. DeleteSheet(" TestSheet "); // 删除Excel中TextSheet表格

 八、 获取Excel中总行数、总列数、当前行

int iCols = SS.GetTotalColumns();   // 总列数
int iRows = SS.GetTotalRows(); // 总行数
int iCurRow = SS.GetCurrentRow(); // 当前所在行号

九、 获取行头数据

CStringArray rowHeader;
SS.GetFieldNames(rowHeader);
CString tmpStr;
for (int i = 0; i < rowHeader.GetSize(); i++)
{
tmpStr.Format("行号: %d, 列号: %d ,内容: %s/n", 1, i+1, rowHeader.GetAt(i));
tempString += tmpStr;
}
AfxMessageBox(tempString);

 

参考文献:
直接通过ODBC读、写Excel表格文件 – 徐景周(译)
A Class to Read and Write to Excel and Text Delimited Spreadsheet – Yap Chun Wei

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【前言】 工作或学习中可能需要实现基于VC读\写Excel文件的功能,本人最近也遇到了该问题。中间虽经波折,但是最终还是找到了解决问题的办法。 在此跟大家分享,希望对跟我同样迷茫过的同学们有所帮助。 1、程序功能 1)打开一个excel文件; 2)显示到CListCtrl上; 3)新建一个Excel文件。 以上均在对话框中实现。 2、平台 VC++2010 3、实现方法 常用的Excel打开方式有两种 1)通过数据库打开; 2)OLE方式打开。 由于方式1)操作繁琐,经常出现莫名的错误,这里选用方式2). 4、准备步骤 首先新建一个Dialog窗体程序,添加list control和两个按钮 1)将ExcelLib文件夹拷贝到程序目录下; 2)将Export2Excel.h,Export2Excel.cpp两个文件添加到项目; 3)包含头文件,#include "ExcelLib/Export2Excel.h" 通过以上步骤在程序中引入了可以读取Excle文件的CExport2Excel类; 5、打开excel文件 通过按钮点击打开 void CExcelTestDlg::OnBnClickedButtonOpenExcel() { //获取文件路径 CFileDialog* lpszOpenFile; CString szGetName; lpszOpenFile = new CFileDialog(TRUE,"","",OFN_FILEMUSTEXIST|OFN_HIDEREADONLY,"Excel File(*.xlsx;*.xls)|*.xls;*.xlsx",NULL); if (lpszOpenFile->DoModal()==IDOK) { szGetName = lpszOpenFile->GetPathName(); SetWindowText(szGetName); delete lpszOpenFile; } else return; //打开文件 //文件中包含多个sheet时,默认打开第一个sheet CExport2Excel Excel_example; Excel_example.OpenExcel(szGetName); //获取sheet个数 int iSheetNum = Excel_example.GetSheetsNumber(); //获取已使用表格行列数 int iRows = Excel_example.GetRowCount(); int iCols = Excel_example.GetColCount(); //获取单元格的内容 CString cs_temp = Excel_example.GetText(1,1); //AfxMessageBox(cs_temp); //List control上显示 //获取工作表列名(第一行) CStringArray m_HeadName; m_HeadName.Add(_T("ID")); for (int i=1;iGetItemCount()>0) { m_list.DeleteColumn(0); } //初始化ClistCtrl,加入列名 InitList(m_list,m_HeadName); //填入内容 //第一行是标题,所以从第2行开始 CString num; int pos; for (int row = 2;row<=iRows; row++) { pos = m_list.GetItemCount(); num.Format(_T("%d"),pos +1); m_list.InsertItem(pos,num); for (int colum=1;columDoModal()==IDOK) { szGetName = lpszOpenFile->GetPathName(); SetWindowText(szGetName); delete lpszOpenFile; } else return; //文件全名称 CString csFileName = szGetName; //需要添加的两个sheet的名称 CString csSheetName = "newSheet"; CString csSheetName2 = "newSheet2"; // 新建一个excel文件,自己写入文字 CExport2Excel Excel_example; //新建excel文件 Excel_example.CreateExcel(csFileName); //添加sheet,新加的sheet在前,也就是序号为1 Excel_example.CreateSheet(csSheetName); Excel_example.CreateSheet(csSheetName2); //操作最开始添加的sheet:(newSheet) Excel_example.SetSheet(2); //添加表头 Excel_example.WriteHeader(1,"第一列"); Excel_example.WriteHeader(2,"第二列"); //添加核心数据 Excel_example.WriteData(1,1,"数据1"); Excel_example.WriteData(1,2,"数据2"); //保存文件 Excel_example.Save(); //关闭文件 Excel_example.Close(); } 7、注意事项 1)一般单个Excel文件包含多个sheet,程序默认打开第一个; 2)指定操作sheet,使用Excel_example.SetSheet(2)函数; 3)打开文件时最左侧的sheet序号为1,新建excel时最新添加的sheet序号为1. 【后记】 本程序主要基于网络CSDN中---“Excel封装库V2.0”---完成,下载地址是:http://download.csdn.net/detail/yeah2000/3576494,在此表示感谢!同时, 1)在其基础上作了小改动,改正了几个小错误,添加了几个小接口; 2)添加了如何使用的例子,原程序是没有的; 3)详细的注释 发现不足之处,还请大家多多指教!
### 回答1: Python可以使用open()函数读取txt文件,然后使用pandas库将数据写入Excel文件。 以下是一个示例代码: ```python import pandas as pd # 读取txt文件 with open('data.txt', 'r') as f: data = f.readlines() # 将数据转换为DataFrame df = pd.DataFrame([line.strip().split('\t') for line in data]) # 将数据写入Excel文件 df.to_excel('data.xlsx', index=False, header=False) ``` 其中,data.txt是要读取的txt文件,data.xlsx是要写入Excel文件。这个示例代码假设txt文件中的数据是以制表符分隔的。如果数据是以其他分隔符分隔的,需要相应地修改代码。 ### 回答2: Python可以轻松读取文本文件,并且可以将数据写入Excel文件中,使用Python处理文本和Excel文件是非常方便的。 读取txt文件 使用Python内置的open()函数打开需要读取的txt文本文件,并且使用read()方法读取整个文件内容,如下所示: ``` f = open('example.txt', 'r') content = f.read() f.close() ``` 读取的内容将存储在变量content中。其中,'example.txt'是需要读取的txt文件名,'r'表示以只读模式打开文件。 如果需要按行读取txt文件,可以使用readline()方法。例如: ``` f = open('example.txt', 'r') for line in f: print(line) f.close() ``` 此代码将打开example.txt文件,并在控制台中打印每一行。对于大型文本文件,这种方法比read()更有效。 写入Excel文件 Python中可以使用很多库来写入Excel文件,包括xlwt、openpyxl和xlutils等。在这里,我们将使用openpyxl库。 要使用openpyxl库,需要使用以下命令来安装它: ``` pip install openpyxl ``` 接下来,您可以使用以下代码创建一个新的Excel文件: ``` from openpyxl import Workbook wb = Workbook() ws = wb.active ws['A1'] = 'Hello' ws['B1'] = 'World!' wb.save('example.xlsx') ``` 此代码将创建一个名为example.xlsx的Excel文件,并将'Hello'和'World!'写入A1和B1单元格中。 要将txt文件中的数据写入Excel文件,可以使用以下代码: ``` from openpyxl import Workbook wb = Workbook() ws = wb.active f = open('example.txt', 'r') row = 1 for line in f: col = 1 for word in line.split(): ws.cell(row=row, column=col, value=word) col += 1 row += 1 f.close() wb.save('example.xlsx') ``` 此代码将打开example.txt,按行读取文件,并将每行中的单词写入Excel文件的单元格中。每行单词将占用Excel文件中的一行,并且将使用split()方法将行分割为单词。 在这里,我们根据读取的每个单元格的行和列号,使用ws.cell()方法将单词写入Excel文件中。最后保存Excel文件。 总结 Python读取txt文件并将数据写入Excel文件非常容易。Python提供了许多库和方法来处理文本和Excel文件。我们可以使用open()函数读取txt文本文件,并使用openpyxl库将数据写入Excel文件中。这种方法非常有效,并且可以处理大型文本和Excel文件。希望本文对大家有所帮助。 ### 回答3: Python是一种强大的编程语言,在数据处理和分析方面具有很大的优势。在数据处理过程中,通常需要将数据从不同的文件格式中转换。一个常见的操作是读取文本文件并将其转换为电子表格格式,这样可以更方便地对数据进行操作和分析。 Python可以通过使用一些库来实现将txt文件写入excel的操作。其中,最常用的库是pandas和openpyxl。 首先,使用pandas库将txt文件读取到pandas的DataFrame中: ``` import pandas as pd df = pd.read_csv('data.txt', delimiter="\t") ``` 这里使用read_csv函数读取txt文件。delimiter参数指定文件中的分隔符,并将文件内容读入一个DataFrame中。 接下来,使用openpyxl库将DataFrame对象写入excel文件中: ``` from openpyxl import Workbook book = Workbook() writer = pd.ExcelWriter('output.xlsx', engine='openpyxl') writer.book = book df.to_excel(writer, sheet_name='Sheet1') writer.save() ``` 在这里,使用openpyxl创建一个新的excel文件,并将它与pandas的ExcelWriter关联。ExcelWriter充当中间层,以帮助将DataFrame写入Excel文件。最后,将DataFrame对象写入到要输出的excel文件中。 以上就是Python读取txt文件写入Excel的基本操作。当然,还可以使用更多的参数和方法来处理和操作数据。此外,还可以使用其他库,如xlwt和xlsxwriter,来实现相同的任务。需要根据实际需求选择适合的方法和工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值