您的位置:首页 > 编程语言 > C#

C#实现Excel跨文件多SHEET合并计算(原创)

2008-02-14 20:45 791 查看
C#实现Excel跨文件多SHEET合并计算

老婆所在的公司有3个分公司, 每个分公司要做一份财务的报表。3个分公司的模板是一样,总公司要将这3个分公司对应的SHEET的对应单元格合并相加。上级给了一个EXCEL文件的模板,这个模板文件真是复杂,共有四五十个SHEET,每个SHEET中还有两个独立的表格。表格中有大量的公式存在。(估计有上百个公式吧)。有公式的地方都进行了加密。

最开始将EXCEL以异构数据库进行处理。但对于一个SHEET中只有一个表格还可以,如果一个SHEET有多个表格,读取到DATATABLE时直接出错。没办法,只好用下面的方式进行处理。

更多文件请参见:

http://hi.csdn.net/xjzdr

以下是CS文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
//using Excel;
using System.Reflection;

namespace TSSH
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

Microsoft.Office.Interop.Excel.Workbook wb1;
System.Collections.ArrayList SheetList = new System.Collections.ArrayList();
Microsoft.Office.Interop.Excel._Worksheet ws1;

private void btnLoad_Click(object sender, EventArgs e)
{
string strFileName = @"F:/模板文件.xls";//打开这个文件,就知道哪些列要进行计算的
Object refmissing = System.Reflection.Missing.Value;
this.axWebBrowser1.Navigate(strFileName, ref refmissing, ref refmissing, ref refmissing, ref refmissing);
//加载并获取所有的SHEET
wb1 = (Microsoft.Office.Interop.Excel.Workbook)axWebBrowser1.Document;

for (int i = 1; i < wb1.Worksheets.Count; i++)
{
ws1 = (Microsoft.Office.Interop.Excel._Worksheet)wb1.Worksheets.get_Item(i);

SheetList.Add(ws1.Name.ToString());

}
this.listBox1.DataSource = this.SheetList;
ws1 = (Microsoft.Office.Interop.Excel._Worksheet)wb1.Worksheets.get_Item(1);
ws1.Activate();
this.Text = ws1.Name.ToString();

}

private void listBox1_Click(object sender, EventArgs e)
{
ws1 = (Microsoft.Office.Interop.Excel._Worksheet)wb1.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());
ws1.Activate();
this.Text = ws1.Name.ToString();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

axWebBrowser1.Dispose();

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ws1 = (Microsoft.Office.Interop.Excel._Worksheet)wb1.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());
ws1.Activate();
this.Text = ws1.Name.ToString();
}

private void textBox2_TextChanged(object sender, EventArgs e)
{
if (this.textBox2.Text != "")
{
this.textBox3.Text = this.textBox2.Text;
}

}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{

}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{

}

private void btnCal_Click(object sender, EventArgs e)
{
int a =0;
int b = 0;
try
{
a = Convert.ToInt32(this.textBox2.Text);
b = Convert.ToInt32(this.textBox3.Text);
if(b>a)
{
MessageBox.Show("请检查输入是否正确!");
}
for (int i = a; i <= b; i++)
{
CAl(i, this.textBox1.Text.ToUpper());
}
MessageBox.Show("计算完成!");
}
catch

{
MessageBox.Show("请检查输入是否正确!");
}

}

private void CAl(int Row_1, string Col_1)
{
string strDescFilePathName_1 = System.Windows.Forms.Application.StartupPath + "//分公司1.xls";
string strDescFilePathName_2 = System.Windows.Forms.Application.StartupPath + "//分公司2.xls";
string strDescFilePathName_3 = System.Windows.Forms.Application.StartupPath + "//分公司3.xls";
string strDescFilePathName_4 = System.Windows.Forms.Application.StartupPath + "//合并后表.xls";

object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.ApplicationClass xlApp_1 = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook_1 = xlApp_1.Workbooks.Open(strDescFilePathName_1, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Microsoft.Office.Interop.Excel._Worksheet ws_1 = (Microsoft.Office.Interop.Excel._Worksheet)xlWorkbook_1.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());

Microsoft.Office.Interop.Excel.ApplicationClass xlApp_2 = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook_2 = xlApp_2.Workbooks.Open(strDescFilePathName_2, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Microsoft.Office.Interop.Excel._Worksheet ws_2 = (Microsoft.Office.Interop.Excel._Worksheet)xlWorkbook_2.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());

Microsoft.Office.Interop.Excel.ApplicationClass xlApp_3 = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook_3 = xlApp_3.Workbooks.Open(strDescFilePathName_3, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Microsoft.Office.Interop.Excel._Worksheet ws_3 = (Microsoft.Office.Interop.Excel._Worksheet)xlWorkbook_3.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());

Microsoft.Office.Interop.Excel.ApplicationClass xlApp_4 = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook_4 = xlApp_3.Workbooks.Open(strDescFilePathName_4, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Microsoft.Office.Interop.Excel._Worksheet ws_4 = (Microsoft.Office.Interop.Excel._Worksheet)xlWorkbook_4.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());

Decimal t_1 = 0;
Decimal t_2 = 0;
Decimal t_3 = 0;

if (((Microsoft.Office.Interop.Excel.Range)ws_1.Cells[Row_1, Col_1]).Text.ToString() == "" || ((Microsoft.Office.Interop.Excel.Range)ws_1.Cells[Row_1, Col_1]).Text == null)
{

t_1 = 0;

}
else
{
t_1 = Convert.ToDecimal(((Microsoft.Office.Interop.Excel.Range)ws_1.Cells[Row_1, Col_1]).Text);

}

if (((Microsoft.Office.Interop.Excel.Range)ws_2.Cells[Row_1, Col_1]).Text.ToString() == "" || ((Microsoft.Office.Interop.Excel.Range)ws_2.Cells[Row_1, Col_1]).Text == null)
{

t_2 = 0;

}
else
{
t_2 = Convert.ToDecimal(((Microsoft.Office.Interop.Excel.Range)ws_2.Cells[Row_1, Col_1]).Text);

}

if (((Microsoft.Office.Interop.Excel.Range)ws_3.Cells[Row_1, Col_1]).Text.ToString() == "" || ((Microsoft.Office.Interop.Excel.Range)ws_3.Cells[Row_1, Col_1]).Text == null)
{

t_3 = 0;

}
else
{
t_3 = Convert.ToDecimal(((Microsoft.Office.Interop.Excel.Range)ws_3.Cells[Row_1, Col_1]).Text);

}

Decimal t = t_1 + t_2 + t_3;
// this.textBox4.Text += "=" + t.ToString();
this.textBox4.AppendText(t_1.ToString()+"+"+t_2.ToString()+"+"+t_3.ToString()+"="+t.ToString());
this.textBox4.AppendText("/n/r/n/r");
try
{
ws_4.Cells[Row_1, Col_1] = t.ToString();

xlWorkbook_4.Save();//保存该xls文件,没有这句话将不会保存数据。
}
catch
{
this.textBox4.AppendText("写入第" + Row_1.ToString() + "行,第" + Col_1 + "列时出错,可能该单元格有计算公式存在。");
this.textBox4.AppendText("/n/r/n/r");
//MessageBox.Show("写入第" + Row_1.ToString() + "行,第" + Col_1+"列时出错。");

}
finally
{
xlWorkbook_4.Save();//保存该xls文件,没有这句话将不会保存数据。

//避免启动多个excel进程。
xlApp_1.Quit();
xlApp_2.Quit();
xlApp_3.Quit();
xlApp_4.Quit();
}
}
}
}

Form1.Designer.cs文件如下:

namespace TSSH
{
partial class Form1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows 窗体设计器生成的代码

/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.textBox4 = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnCal = new System.Windows.Forms.Button();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.btnLoad = new System.Windows.Forms.Button();
this.splitContainer2 = new System.Windows.Forms.SplitContainer();
this.listBox1 = new System.Windows.Forms.ListBox();
this.axWebBrowser1 = new AxSHDocVw.AxWebBrowser();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.splitContainer2.Panel1.SuspendLayout();
this.splitContainer2.Panel2.SuspendLayout();
this.splitContainer2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).BeginInit();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.textBox4);
this.splitContainer1.Panel1.Controls.Add(this.label3);
this.splitContainer1.Panel1.Controls.Add(this.textBox3);
this.splitContainer1.Panel1.Controls.Add(this.label2);
this.splitContainer1.Panel1.Controls.Add(this.label1);
this.splitContainer1.Panel1.Controls.Add(this.btnCal);
this.splitContainer1.Panel1.Controls.Add(this.textBox2);
this.splitContainer1.Panel1.Controls.Add(this.textBox1);
this.splitContainer1.Panel1.Controls.Add(this.btnLoad);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
this.splitContainer1.Size = new System.Drawing.Size(1091, 409);
this.splitContainer1.SplitterDistance = 82;
this.splitContainer1.TabIndex = 0;
//
// textBox4
//
this.textBox4.Dock = System.Windows.Forms.DockStyle.Right;
this.textBox4.Location = new System.Drawing.Point(641, 0);
this.textBox4.Multiline = true;
this.textBox4.Name = "textBox4";
this.textBox4.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBox4.Size = new System.Drawing.Size(450, 82);
this.textBox4.TabIndex = 9;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(356, 20);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(89, 12);
this.label3.TabIndex = 8;
this.label3.Text = "要合并的终止行";
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(358, 38);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(85, 21);
this.textBox3.TabIndex = 7;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(256, 20);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(89, 12);
this.label2.TabIndex = 6;
this.label2.Text = "要合并的起始行";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(135, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(113, 12);
this.label1.TabIndex = 5;
this.label1.Text = "要合并的列(字母)";
//
// btnCal
//
this.btnCal.Location = new System.Drawing.Point(449, 38);
this.btnCal.Name = "btnCal";
this.btnCal.Size = new System.Drawing.Size(75, 23);
this.btnCal.TabIndex = 4;
this.btnCal.Text = "合并计算";
this.btnCal.UseVisualStyleBackColor = true;
this.btnCal.Click += new System.EventHandler(this.btnCal_Click);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(258, 38);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(85, 21);
this.textBox2.TabIndex = 3;
this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(135, 38);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 21);
this.textBox1.TabIndex = 2;
this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
//
// btnLoad
//
this.btnLoad.Location = new System.Drawing.Point(33, 34);
this.btnLoad.Name = "btnLoad";
this.btnLoad.Size = new System.Drawing.Size(75, 23);
this.btnLoad.TabIndex = 0;
this.btnLoad.Text = "加载";
this.btnLoad.UseVisualStyleBackColor = true;
this.btnLoad.Click += new System.EventHandler(this.btnLoad_Click);
//
// splitContainer2
//
this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer2.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer2.Location = new System.Drawing.Point(0, 0);
this.splitContainer2.Name = "splitContainer2";
//
// splitContainer2.Panel1
//
this.splitContainer2.Panel1.Controls.Add(this.listBox1);
//
// splitContainer2.Panel2
//
this.splitContainer2.Panel2.Controls.Add(this.axWebBrowser1);
this.splitContainer2.Size = new System.Drawing.Size(1091, 323);
this.splitContainer2.SplitterDistance = 193;
this.splitContainer2.TabIndex = 1;
//
// listBox1
//
this.listBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.listBox1.Font = new System.Drawing.Font("宋体", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.listBox1.FormattingEnabled = true;
this.listBox1.ItemHeight = 14;
this.listBox1.Location = new System.Drawing.Point(0, 0);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(193, 312);
this.listBox1.TabIndex = 3;
this.listBox1.SelectedIndexChanged += new System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.Click += new System.EventHandler(this.listBox1_Click);
//
// axWebBrowser1
//
this.axWebBrowser1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axWebBrowser1.Enabled = true;
this.axWebBrowser1.Location = new System.Drawing.Point(0, 0);
this.axWebBrowser1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axWebBrowser1.OcxState")));
this.axWebBrowser1.Size = new System.Drawing.Size(894, 323);
this.axWebBrowser1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1091, 409);
this.Controls.Add(this.splitContainer1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Load += new System.EventHandler(this.Form1_Load);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.splitContainer2.Panel1.ResumeLayout(false);
this.splitContainer2.Panel2.ResumeLayout(false);
this.splitContainer2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.axWebBrowser1)).EndInit();
this.ResumeLayout(false);

}

#endregion

private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.Button btnLoad;
private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.ListBox listBox1;
private AxSHDocVw.AxWebBrowser axWebBrowser1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button btnCal;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox4;
}
}

//说明:

在界面上以WEBBROWSE加载一个模板文件,这样就知道哪些列和行需要合并的。

输入对应的行和列,就可以进行合并计算并写入合并后的文件中。

在EXCEL中,还有另一个跨文件进行EXCEL合并计算的方法。

“数据/合并计算”通过引用其它的EXCEL文件,也可以达到合算的目的。只是根据我的需要,制作了一个简单的程序。很多错误及异常没有处理。

补充:

因为每个月都要做一次报表,这样工作量仍是很大。

想了个好办法,用程序将每一个需要合并的单元格中写入计算公式,这样,数据就自动计算了。

/// <summary>
/// 填写合并计算公式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMegerExpress_Click(object sender, EventArgs e)
{
int a = 0;
int b = 0;
try
{
a = Convert.ToInt32(this.textBox2.Text);
b = Convert.ToInt32(this.textBox3.Text);
if (b > a)
{
MessageBox.Show("请检查输入是否正确!");
}
for (int i = a; i <= b; i++)
{
CAlExpress(i, this.textBox1.Text.ToUpper());
}
MessageBox.Show("计算完成!");
}
catch
{
MessageBox.Show("请检查输入是否正确!");
}

}

该按钮调用的方法:

private void CAlExpress(int Row_1, string Col_1)
{

string strSheetName = this.listBox1.SelectedValue.ToString();

string strDescFilePathName_4 = System.Windows.Forms.Application.StartupPath + "//合并后表.xls";
string strExpress = "='" + System.Windows.Forms.Application.StartupPath + @"/[天翼.xls]"+strSheetName+"'!" + Col_1.ToUpper() + Row_1 ;
strExpress += "+'" + System.Windows.Forms.Application.StartupPath + @"/[天筑.xls]" + strSheetName + "'!" + Col_1.ToUpper() + Row_1;
strExpress += "+'" + System.Windows.Forms.Application.StartupPath + @"/[独山子.xls]" + strSheetName + "'!" + Col_1.ToUpper() + Row_1;
Console.WriteLine(strExpress);
this.textBox4.AppendText("写入第" + Row_1.ToString() + "行,第" + Col_1 + "列的公式是:" + "/n/r/n/r" + strExpress);
this.textBox4.AppendText("/n/r/n/r");
object oMissing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.ApplicationClass xlApp_4 = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook_4 = xlApp_4.Workbooks.Open(strDescFilePathName_4, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Microsoft.Office.Interop.Excel._Worksheet ws_4 = (Microsoft.Office.Interop.Excel._Worksheet)xlWorkbook_4.Worksheets.get_Item(this.listBox1.SelectedValue.ToString());

try
{

ws_4.Cells[Row_1, Col_1] = strExpress;

xlWorkbook_4.Save();//保存该xls文件,没有这句话将不会保存数据。
this.textBox4.AppendText("写入第" + Row_1.ToString() + "行,第" + Col_1 + "列时成功。");
}
catch
{
this.textBox4.AppendText("写入第" + Row_1.ToString() + "行,第" + Col_1 + "列时出错,可能该单元格有计算公式存在。");
this.textBox4.AppendText("/n/r/n/r");
//MessageBox.Show("写入第" + Row_1.ToString() + "行,第" + Col_1+"列时出错。");

}
finally
{
xlWorkbook_4.Save();//保存该xls文件,没有这句话将不会保存数据。

//避免启动多个excel进程。

xlApp_4.Quit();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐