WPF读写excel的完整示例-excel文件合并工具

using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Windows;

namespace excel文件合并工具
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();

// 在此点下面插入创建对象所需的代码。
}

//选择文件夹
private void but1_Click( object sender, System.Windows.RoutedEventArgs e)
{
// 在此处添加事件处理程序实现。
System.Windows.Forms.FolderBrowserDialog fd = new System.Windows.Forms.FolderBrowserDialog();
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
lbl1.Text = fd.SelectedPath;
}

//读取文件夹下的所有xls文件
private void but2_Click( object sender, System.Windows.RoutedEventArgs e)
{
// 在此处添加事件处理程序实现。
if (lbl1.Text == string.Empty || lbl2.Text == string.Empty)
{
MessageBox.Show( "文件路径和工作表名不能为空", "注意", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
string[] strs=Directory.GetFiles(lbl1.Text, "*.xls");
string err = string.Empty;
DataTable rt = new DataTable();
foreach ( string s in strs)
{
string strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + s + ";
Extended Properties=/"Excel 8.0;HDR=No;IMEX=1;/""
;
OleDbConnection conn = new OleDbConnection(strconn);
string sql = "SELECT * FROM [" + lbl2.Text + "$]";
OleDbDataAdapter adp = new OleDbDataAdapter(sql,conn);
DataTable dt = new DataTable();
try
{
adp.Fill(dt);
}
catch
{
err += s + ",";
}
finally
{
conn.Close();
}
rt.Load( new DataTableReader(dt));
}
grid1.ItemsSource = rt.DefaultView;
grid1.CanUserAddRows = false;
if (err != string.Empty)
MessageBox.Show( "以下文件在合并时出现问题,请检查其文件格式是否正确/n"+err, "注意",MessageBoxButton.OK,MessageBoxImage.Information);
}

//导出为新的xls文件
private void but2_Copy_Click( object sender, System.Windows.RoutedEventArgs e)
{
// 在此处添加事件处理程序实现。
System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
sf.Filter = "excel 文档|*.xls";
if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
FileStream fs = new FileStream(sf.FileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
DataTable dt = (grid1.ItemsSource as DataView).Table;
foreach (DataRow dr in dt.Rows)
{
string line = string.Empty;
foreach (DataColumn dc in dt.Columns)
{
line += dr[dc] + "/t";
}
sw.WriteLine(line);
}
sw.Close();
fs.Close();
MessageBox.Show( "数据已经成功导出!", "注意", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
}

  最近在工作中经常的使用excel的vlookup()函数找数据,有些数据是分散在不同的表格中,粘贴复制麻烦,弄了个小工具对同一文件夹下的文件进行合并。

  excel文件合并工具下载

本文来自何苦上青天的博客,原文地址:http://www.cnblogs.com/861580030/archive/2011/05/10/2042305.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值