c#操作excel

说明

vs2022开发,调用excel

代码

csharp 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace ExcelReplace
{
    public partial class Form1 : Form
    {
        private Microsoft.Office.Interop.Excel.Application app;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnPath_Click(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tbPath.Text = this.openFileDialog1.FileName;
            }
        }

        private void btnReplace_Click(object sender, EventArgs e)
        {
            if (tbPath.Text.Trim().Length == 0)
            {
                MessageBox.Show("请选择Excel文件");
                return; 
            }

            //替换
            app=new Microsoft.Office.Interop.Excel.Application();
            app.Visible = true;

            var wb=app.Workbooks.Open(tbPath.Text);
            foreach (Worksheet ws in wb.Worksheets)
            {
                //使用的行数
                var rowCount =ws.UsedRange.Rows.Count;
                //使用的列数
                var colCount=ws.UsedRange.Columns.Count;

                for (int row = 1; row <= rowCount; row++)
                {
                    for (int col = 1; col <= colCount; col++)
                    {
                        Range c=ws.Cells[row, col];
                        string s = c.Text;

                        if (s.Contains("亿"))
                        {
                            string s1 = "=" + s.Replace("亿", "*10000");

                            c.Formula = s1;
                        } else if (s.Contains("万"))
                        {
                            string s1 = s.Replace("万", "");

                            c.Value = s1;
                        }
                    }
                }
            }


            //保存文件
            FileInfo f=new FileInfo(tbPath.Text);
            string path = f.DirectoryName+"\\" + f.Name.Replace(f.Extension, "") + DateTime.Now.ToString("yyyyMMddHHmmss") + f.Extension;
            wb.SaveAs(path);

            //关闭
            wb.Close();

            //退出excel
            app.Quit();

            MessageBox.Show("处理完成,保存文件为:" + path);
        }
    }
}
相关推荐
Mr_sun.9 分钟前
Day09——入退管理-入住-2
android·java·开发语言
MAGICIAN...20 分钟前
【java-软件设计原则】
java·开发语言
gpfyyds66629 分钟前
Python代码练习
开发语言·python
CodeKwang42 分钟前
Qt实战:简易Excel表格 | 附完整源码
qt·excel·qtabwidget·qt控件
盐真卿44 分钟前
python第八部分:高级特性(二)
java·开发语言
茉莉玫瑰花茶1 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法
lly2024061 小时前
《堆的 shift down》
开发语言
czhc11400756631 小时前
通信 28
c#
黎雁·泠崖1 小时前
【魔法森林冒险】2/14 抽象层设计:Figure/Person类(所有角色的基石)
java·开发语言
季明洵2 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表