读取Excel中的内容,并写入txt文件中

这是一个简单的应用程序,用于将Excel文件中的内容转换成文本文件。通过选择Excel文件并指定输出的文本文件名,程序能够读取Excel数据并将其写入指定的TXT文件中。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;

//**********************************************
//程式设计:殷庆飞
//设计时间:2007-8-10
//功能描述:读取Excel中的内容,并写入txt文件中
//修改人:
//修改描述:
//修改时间:
//修改描述:
//***********************************************

namespace 文件格式转换
{
public partial class Form1 : Form
{
OleDbConnection cn;
DataSet MyDataSet;

public Form1()
{
InitializeComponent();
}

//浏览按钮,选择要读取的EXCEL文件
private void btnFind_Click(object sender, EventArgs e)
{
txtName.Text = "";
OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*";
openFile.ShowDialog();
if (txtName.Text == string.Empty) txtName.Text = openFile.FileName;
}

//转换按钮,将Excel中的内容转换到文本文件中
private void btnConvert_Click(object sender, EventArgs e)
{
try
{
if (txtName.Text == string.Empty || txtConName.Text == string.Empty)//判断是否选择了要读到的Excel,是否输入了转换后的txt文件名称
{
MessageBox.Show("注意:选择要转换的Excel,并输入转换后的文本文件名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
cn = GetExcelConnection(txtName.Text.Trim(), false, 1);
if (cn != null)
{
cn.Open();
MyDataSet = ExecuteDataSet(cn);
if (MyDataSet != null)
{
string strPath = Application.StartupPath + @"\" + txtConName.Text.Trim() + ".txt";

if (File.Exists(strPath))
{
if (MessageBox.Show("文件:" + txtConName.Text + "已经存在!是否要删除?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
{
File.Delete(strPath);
}
else
{
MessageBox.Show("请输入其它的名称", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
txtConName.Focus();
return;
}
}

FileStream fs = new FileStream(strPath, FileMode.CreateNew, FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs);
string strContent = "";

for (int i = 0; i < MyDataSet.Tables.Count; i++)//Excel中sheet的个数
{
for (int row = 0; row < MyDataSet.Tables[i].Rows.Count; row++)
{
strContent = "";
for (int col = 0; col < MyDataSet.Tables[i].Columns.Count; col++)//sheet中列的个数
{
if (col == 1)
{
strContent += MyDataSet.Tables[i].Rows[row][col].ToString() + " ";
}
else
{
strContent += MyDataSet.Tables[i].Rows[row][col].ToString();
}
}
sw.WriteLine(strContent);
}
}
sw.Close();//关闭文件
MessageBox.Show("转换成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("连接Excel发生错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (Exception ex)
{
string strError = string.Format("错误:{0}", ex.Message);
MessageBox.Show(strError, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
}

//退出
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}


/**//// <summary>
/// 获取 Excel 连接对象。
/// </summary>
/// <param name="strFullPath">文件的完全路径</param>
/// <param name="isTreatedHeader">是否处理表头</param>
/// <param name="intIMEXMode">输入输出模式。1:设置输入为文本 Text 类型,通常使用该值。0/2:设置输入为 多数 Majority 类型,此设置极易导致数据缺失发生。</param>
/// <returns>Excel 连接对象</returns>
public static OleDbConnection GetExcelConnection( string strFullPath, bool isTreatedHeader, int intIMEXMode )
{
try
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1};IMEX={2};'";
string strTreatedHeader = string.Empty;

if (isTreatedHeader) strTreatedHeader = "Yes";
else strTreatedHeader = "No";

connectionString = string.Format(connectionString, strFullPath, strTreatedHeader, intIMEXMode);

return new OleDbConnection(connectionString);
}
catch (Exception ex)
{
string strError = string.Format("错误:{0}", ex.Message);
MessageBox.Show(strError, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}

}


/**//// <summary>
/// 读取给定连接中全部或给定表的内容至 DataSet。
/// </summary>
/// <param name="cn">给定连接</param>
/// <param name="sheetNames">[可选参数]指定表名 的 sheet</param>
/// <returns>包含全部或给定 Sheet 数据的 DataSet</returns>
public static DataSet ExecuteDataSet( OleDbConnection cn, params string[] sheetNames )
{
try
{
DataSet ds = new DataSet();

DataTable schemaTable = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string queryString;

// 带 $ 的表名
string fullTableName;

// 不带 $ 的表名
string realTableName;

OleDbDataAdapter odda = new OleDbDataAdapter();

foreach (DataRow dr in schemaTable.Rows)
{
fullTableName = dr["TABLE_NAME"].ToString();

realTableName = fullTableName.Remove(fullTableName.Length - 1, 1);

// 根据给定表导入
if (sheetNames.Length > 0)
{
// 若当前表不在给定表数组中,则不填充到数据集中。
if (Array.IndexOf(sheetNames, realTableName) < 0)
{
continue;
}
}

queryString = string.Format("SELECT * FROM [{0}]", fullTableName);

odda.SelectCommand = new OleDbCommand(queryString, cn);
odda.Fill(ds, realTableName);
}

return ds;
}
catch (Exception ex)
{
string strError = string.Format("错误:{0}", ex.Message);
MessageBox.Show(strError, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return null;
}
}

//打开关于框
private void btnAbout_Click(object sender, EventArgs e)
{
frmAbout frm = new frmAbout();
frm.ShowDialog();
}

}
}

可到这里去下载http://download.youkuaiyun.com/source/225379

【前言】 工作或学习中可能需要实现基于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. 【后记】 本程序主要基于网络优快云中---“Excel封装库V2.0”---完成,下载地址是:http://download.csdn.net/detail/yeah2000/3576494,在此表示感谢!同时, 1)在其基础上作了小改动,改正了几个小错误,添加了几个小接口; 2)添加了如何使用的例子,原程序是没有的; 3)详细的注释 发现不足之处,还请大家多多指教!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值