WPF-两份excel文档列自动匹配导入工具-技术&分享

WPF-两份excel文档列自动匹配导入工具-技术&分享

A文档中包含两列x,y(x与y对应);B文档包含一列y,需要将A文档的y匹配B文档的y,将A文档的x内容匹配到B文档中,与B文档中的y列对应。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using Mysoft.Common.Multithread;
using System.Xml;
using Aspose.Cells;
using NPOI.SS.UserModel;

namespace 导入BUG编号_Excel2013
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
         private void btnOpenFile1_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
            openFile.Filter = "*.xlsx|*.xlsx";
            openFile.Title = "选择标准版路径";
            openFile.ShowDialog();
            txtBaseExcelPath.Text = openFile.FileName;
        }

        private void btnOpenFile2_Click(object sender, RoutedEventArgs e)
        {

            FolderBrowserDialog openFolder = new FolderBrowserDialog();
            openFolder.ShowDialog();
            txtImportExcelPath.Text = openFolder.SelectedPath;
        }

        private void btnOutputBugNo_Click(object sender, RoutedEventArgs e)
        {
            if (txtBaseExcelPath.Text == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("请选择含BUG编号的文档!");
                System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
                openFile.Filter = "*.xlsx|*.xlsx";
                openFile.Title = "选择标准版路径";
                openFile.ShowDialog();
                return;
            }
            if (txtOutputItemColumn.Text=="")
            {
                System.Windows.Forms.MessageBox.Show("请填写主题列名称!");
                    return;
            }
            if (txtOutputItemColumn.Text.Split(‘;‘).Length>2)
            {
                System.Windows.Forms.MessageBox.Show("最多填写两个主题列名称!");
                return;
            }
            if (txtBugNoColumn.Text == "")
            {
                System.Windows.Forms.MessageBox.Show("请填写编号列名称!");
                return;
            }
            OutputBugNo outputBugNo = new OutputBugNo();
            if (outputBugNo.Build(txtBaseExcelPath.Text, txtOutputItemColumn.Text, txtBugNoColumn.Text))
            {
                System.Windows.Forms.MessageBox.Show("导出BUG编号成功!");
            }
        }

        private void btnImportBugNo_Click(object sender, RoutedEventArgs e)
        {
            if (txtImportExcelPath.Text == string.Empty)
            {
                System.Windows.Forms.MessageBox.Show("请选择需导入BUG编号的文件夹!");
                FolderBrowserDialog openFolder = new FolderBrowserDialog();
                openFolder.ShowDialog();
                return;
            }
            if (txtImportItemColumn.Text=="")
            {
                System.Windows.Forms.MessageBox.Show("请填写导入文档的主题列名称!");
                    return;
            }
            ImportBugNo ImportBugNo = new ImportBugNo();
            if (ImportBugNo.Build(txtImportExcelPath.Text,txtImportItemColumn.Text))
            {
                System.Windows.Forms.MessageBox.Show("导入BUG编号成功!");
            }

        }

        public class OutputBugNo : IBackgroundExecute
        {
            private string _errorMessage;
            private string _outputItemColumn;
            private string _BugNoColumn;
            public string ErrorMessage
            {
                get { throw new NotImplementedException(); }
            }
            private string _filePath;
            public event UpdateStepDelegate OnUpdateStep;

            public event PerformStepDelegate OnPerformStep;

            public bool Exec()
            {

                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(AppDomain.CurrentDomain.BaseDirectory + "BugNo.xml");
                    doc.SelectSingleNode("//Mysoft.Data").InnerText="";
                    LoadExcelToXml(doc, _filePath);
                    doc.Save(AppDomain.CurrentDomain.BaseDirectory + "BugNo.xml");

                    //OnUpdateStep(this, new UpdateStepEventArg() { StepMaxCount = diffFileNameList.Count, StepInfo = "导出BUG清单" });
                    ////读取冲突清单
                    //IWorkbook workbookColide;
                    //using (FileStream fs = new FileStream(_colideFileName, FileMode.Open, FileAccess.Read))
                    //{
                    //    workbookColide = WorkbookFactory.Create(fs);
                    //}
                    //ISheet shtColide = workbookColide.GetSheetAt(0);
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return false;
                }
                return true;
            }

            public bool Build(string filePath, string outputItemColumn, string BugNoColumn)
            {
                try
                {
                    _filePath = filePath;
                    _outputItemColumn    = outputItemColumn;
                    _BugNoColumn = BugNoColumn;
                    ProgressRun progressRun = new ProgressRun();
                    if (!progressRun.Run(this, 1))
                    {
                        System.Windows.Forms.MessageBox.Show(_errorMessage);
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                return true;
            }

            public void LoadExcelToXml(XmlDocument doc, string fileName)
            {
                    Array Item = _outputItemColumn.Split(‘;‘);
                    IWorkbook workbook;
                    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                    {
                        workbook = WorkbookFactory.Create(fs);
                    }

                    ISheet sht = (ISheet)workbook.GetSheetAt(0);
                    IRow shtRow;
                    ICell shtCell;
                    int problemItemIndex = -1;
                    int bugItemIndex = -1;
                    int bugNoIndex = -1;
                    if (sht == null)
                    {
                        return;
                    }
                    int rowCount = sht.PhysicalNumberOfRows;
                    shtRow = (IRow)sht.GetRow(0);
                for (int k = 0; k < shtRow.PhysicalNumberOfCells; k++)
                {
                    shtCell = (ICell) shtRow.GetCell(k);

                    if (shtCell == null)
                    {
                        continue;
                    }
                    if (Item.Length == 2)
                    {
                        if (Item.GetValue(0).ToString().IndexOf(shtCell.ToString()) >= 0) //问题主题
                        {
                            problemItemIndex = k;
                        }
                        if (Item.GetValue(1).ToString().IndexOf(shtCell.ToString()) >= 0) //BUG解决方案标题
                        {
                            bugItemIndex = k;
                        }
                    }
                    else if (Item.Length == 1)
                    {
                        if (Item.GetValue(0).ToString()==shtCell.ToString()) //问题主题"
                        {
                            problemItemIndex = k;
                        }
                    }
                    if (_BugNoColumn==shtCell.ToString()) //主动修复编号"
                    {
                        bugNoIndex = k;
                    }

                    if (problemItemIndex == -1 || bugNoIndex == -1 || bugItemIndex == -1)
                    {
                        continue;
                    }
                }
                if (problemItemIndex==-1 && bugItemIndex==-1)
                {
                    _errorMessage = "主题列填写错误";
                    return;
                }
                if (bugNoIndex == -1)
                {
                    _errorMessage = "编号列填写错误";
                    return;
                }
                for (int j = 1; j < rowCount; j++)
                {
                    string bugItemTitel="";
                    bool bugItem = false;
                    shtRow = (IRow)sht.GetRow(j);
                    if (shtRow == null) { continue; }
                    if (shtRow.GetCell(problemItemIndex) == null || shtRow.GetCell(bugNoIndex) == null)
                    {
                        break;
                    }
                    string problemItemTitle = shtRow.GetCell(problemItemIndex).ToString();

                    string bugNo = shtRow.GetCell(bugNoIndex).ToString();
                    if (bugItemIndex != -1)
                    {
                        if (shtRow.GetCell(bugItemIndex) != null)
                        {
                            bugItemTitel = shtRow.GetCell(bugItemIndex).ToString();
                            bugItem = true;
                        }
                    }

                    if (bugNo != string.Empty)
                    {
                        XmlNode bugNoNode = doc.SelectSingleNode("//BugNo[@problemItem=‘" + problemItemTitle + "‘]");
                        if (bugNoNode == null)
                        {
                            XmlElement bugNoElement = doc.CreateElement("BugNo");
                            bugNoElement.SetAttribute("problemItemTitle", problemItemTitle);
                            if (bugItem)
                            {
                                bugNoElement.SetAttribute("bugItemTitel", bugItemTitel);
                            }
                            bugNoElement.InnerText = bugNo;
                            doc.DocumentElement.AppendChild(bugNoElement);
                        }
                        else
                        {
                            bugNoNode.InnerText = bugNo;
                        }
                    }
                }

            }
        }
        public class ImportBugNo : IBackgroundExecute
        {
            private string _errorMessage;
            private string _folder;
            private string _importItemColumn;
            private int _BugNoColumn;
            public string ErrorMessage
            {
                get { throw new NotImplementedException(); }
            }
            public event UpdateStepDelegate OnUpdateStep;
            public event PerformStepDelegate OnPerformStep;
            private XmlDocument _doc;
            public bool Exec()
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(AppDomain.CurrentDomain.BaseDirectory + "BugNo.xml");
                    _doc = doc;
                    OnUpdateStep(this, new UpdateStepEventArg() { StepMaxCount = Directory.GetFiles(_folder).Count(), StepInfo = "导入BUG编号" });

                    if (!ImportExcelBugNo(_doc, _folder))
                        return false;
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return false;
                }
                return true;
            }
            public bool Build(string folder,string importItemColumn)
            {
                try
                {
                    _folder = folder;
                    _importItemColumn = importItemColumn;
                    ProgressRun progressRun = new ProgressRun();
                    if (!progressRun.Run(this, 1))
                    {
                        System.Windows.MessageBox.Show(_errorMessage);
                        return false;
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    System.Windows.MessageBox.Show(ex.Message);
                    return false;
                }
            }

            public string MatchBugNo(string excelTitle)//匹配BUG编号
            {
                string bugNo = "无";
                string xmlBUGTitle = "";
                string xmlProblemTitle = "";
                try
                {
                    if (excelTitle.Trim().Equals(""))
                    {
                        return bugNo;
                    }
                    XmlNodeList nodelist = _doc.SelectNodes("//Mysoft.Data//BugNo");
                    foreach (XmlNode node in nodelist)
                    {
                        try
                        {
                            xmlProblemTitle = node.Attributes["problemItemTitle"].Value;
                        }
                        catch (Exception)
                        {

                            xmlProblemTitle = "";
                        }

                        try
                        {
                            xmlBUGTitle = node.Attributes["bugItemTitel"].Value;
                        }
                        catch (Exception)
                        {

                            xmlBUGTitle = "";
                        }

                        string bugNoValue = node.InnerText;
                        if (xmlProblemTitle!="")
                        {
                            if (xmlProblemTitle.Trim().Equals(""))
                            {
                                continue;
                            }
                            if (excelTitle.IndexOf("】") > -1 && excelTitle.IndexOf("【") == 0)//去掉第一个【xxx】的内容
                            {
                                excelTitle = excelTitle.Substring(excelTitle.IndexOf("】"), excelTitle.Length - excelTitle.IndexOf("】") - 1);
                            }
                            if (xmlProblemTitle.IndexOf("】") > -1 && xmlProblemTitle.IndexOf("【") == 0)
                            {
                                xmlProblemTitle = xmlProblemTitle.Substring(xmlProblemTitle.IndexOf("】"), xmlProblemTitle.Length - xmlProblemTitle.IndexOf("】") - 1);
                            }
                            if (xmlProblemTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")
                                .IndexOf(excelTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")) >= 0 ||
                                excelTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")
                                .IndexOf(xmlProblemTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")) >= 0)
                            {
                                bugNo = bugNoValue;
                                break;
                            }
                        }
                        if (xmlBUGTitle!="")
                        {
                            if (xmlBUGTitle.Trim().Equals(""))
                            {
                                continue;
                            }
                            if (excelTitle.IndexOf("】") > -1 && excelTitle.IndexOf("【") == 0)
                            {
                                excelTitle = excelTitle.Substring(excelTitle.IndexOf("】"), excelTitle.Length - excelTitle.IndexOf("】") - 1);
                            }
                            if (xmlBUGTitle.IndexOf("】") > -1 && xmlBUGTitle.IndexOf("【") == 0)
                            {
                                xmlBUGTitle = xmlBUGTitle.Substring(xmlBUGTitle.IndexOf("】"), xmlBUGTitle.Length - xmlBUGTitle.IndexOf("】") - 1);
                            }
                            if (xmlBUGTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")
                                .IndexOf(excelTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")) >= 0 ||
                                excelTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")
                                .IndexOf(xmlBUGTitle.Trim().Replace(":", "").Replace(":", "").Replace("[", "").Replace("【", "").Replace("】", "").Replace("]", "").Replace(",", "").Replace("。", "")) >= 0)
                            {
                                bugNo = bugNoValue;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;

                }
                return bugNo;
            }

            public bool ImportExcelBugNo(XmlDocument doc,string folder)
            {
                try
                {
                    if (!Directory.Exists(folder))
                    {
                        _errorMessage = "所选目录不存在!请重新选择目录";
                        return false;
                    }
                    foreach(string file in Directory.GetFiles(folder))
                    {

                        if(file.Substring(file.LastIndexOf(".")+1,file.Length-file.LastIndexOf(".")-1)=="xlsx"||file.Substring(file.LastIndexOf(".")+1,file.Length-file.LastIndexOf(".")-1)=="xls")
                        {
                            Aspose.Cells.Workbook wk = new Aspose.Cells.Workbook();
                            //wk.Initialize();
                            wk.Open(file);
                            Worksheet sht = wk.Worksheets[0];//查看文档的sheet0内容
                            Cells cells = sht.Cells;//获取sheet0的所有单元格
                            int titleIndex = -1;
                            int bugNoIndexEdit = -1;
                            int bugNoIndexAdd = -1;
                            string title;
                            if (sht==null)
                            {
                                return false;
                            }
                            int rowCount = cells.MaxDataRow+1;
                            int cellCount = cells.MaxDataColumn + 1;
                            Dictionary<string, int> titleToIndex = new Dictionary<string, int>();
                            if (rowCount == 0)
                            {
                                continue;
                            }
                            for (int k = 0; k < cellCount; k++)
                            {
                                if (cells[0, k].Value == null)
                                {
                                    continue;
                                }
                                else
                                 {
                                    title = cells[0, k].Value.ToString();
                                    if (title == _importItemColumn || title == "主动修复编号")
                                    {
                                        if (title == "主动修复编号")
                                        {
                                            _BugNoColumn = k;
                                        }
                                        if (!titleToIndex.Keys.Contains(title))
                                        {
                                            titleToIndex.Add(title, k);
                                        }
                                    }
                                }
                            }
                            bool existTitle = false;
                            foreach (var VARIABLE    in titleToIndex.Keys)
                            {
                                if (VARIABLE.IndexOf(_importItemColumn) > -1)
                                {
                                    existTitle = true;
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            if(!existTitle)
                            {
                                _errorMessage = "文档" + file + "不包含" + _importItemColumn;
                                continue;
                            }

                            bool existBugNo= false;
                            foreach (var VARIABLE    in titleToIndex.Keys)
                            {
                                if (VARIABLE.IndexOf("主动修复编号") > -1)
                                {
                                    existBugNo = true;
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            if(!existBugNo)
                            {
                                _BugNoColumn = cells.MaxDataColumn + 1;
                                cells.InsertColumn(_BugNoColumn);
                                Cell cell = cells[0, _BugNoColumn];
                                cell.PutValue("主动修复编号");
                            }

                            for (int j = 1; j < rowCount; j++)
                            {
                                if (cells[j, 0] == null)
                                {
                                    continue;
                                }
                                Cell cell = cells[j,titleToIndex[_importItemColumn]];
                                if (cell == null)
                                {
                                    break;
                                }
                                if (cell.Value != string.Empty)
                                {
                                    string BugNo = MatchBugNo(cell.ToString());

                                    cell = cells[j, _BugNoColumn];
                                    cell.PutValue(BugNo);
                                }
                            }
                            wk.Save(file, SaveFormat.Xlsx);
                        }
                    }
                    OnPerformStep(this, PerformStepEventArg.SingleStepArg);
                }

                catch(Exception ex)
                {
                    _errorMessage = ex.Message;
                    return false;
                }
                return true;
            }
        }

    }
}

WPF-两份excel文档列自动匹配导入工具-技术&分享

时间: 2024-10-25 20:44:20

WPF-两份excel文档列自动匹配导入工具-技术&分享的相关文章

如何破解Excel文档的编辑密码

对于Excel文档我们不仅可以设置打开密码,还可以设置几天几种密码,比如编辑密码.编辑密码又称写保护密码,是一种可以限制编辑权限的密码.如果我们在日常工作中发现自己忘记了excel编辑密码的话,那就需要想办法恢复.今天跟大家主要探讨的就是如何使用office密码破解工具恢复Excel文档的编辑密码.下面就来分享如何破解Excel文档的编辑密码? 设置Excel文档的编辑密码 打开需要设置的编辑密码的Excel文档,依次选择“工具->选项->安全性”或者点击左上角的“WPS表格”选择文件信息-&

Excel文档间的数据替换 ---电脑版APP 自动操作魔法师

http://www.won-soft.com/macro/solution/excel-data-replace.htm 介绍: 在我们的日常工作中, 可能经常需要使用同各种数据表格打交道.比如财务工作中各种数据表格, 生产管理上的各种生产数据统计表,以前人力资源部的工资表等等.在处理这些数据的过程中, 我们可能经常会遇到要做一张表,但这张表的数据需要从另一张表上取,每个数据间有一些相关联的规则,举例来说: 年底一般都会做工资统计表,列出所有员工的全年的各种奖金总计.全年应发工资.实发工资.扣

后台生成EXCEL文档,自定义列

后台生成EXCEL文档,自定义列 //response输出流处理 //设置编码.类型.文件名 getResponse().reset(); getResponse().setCharacterEncoding("utf-8"); getResponse().setContentType("application/vnd.ms-excel"); String useragent = getRequest().getHeader("user-agent&quo

PHP读取excel文档

PHP读取excel文档 项目需要读取Excel的内容,从百度搜索了下,主要有两个选择,第一个是PHPExcelReader,另外一个是PHPExcel. PHPExcelReader比较轻量级,仅支持Excel的读取,实际上就是一个Reader.但是可惜的是不能够支持Excel 2007的格式(.xlsx). PHPExcel比较强大,能够将内存中的数据输出成Excel文件,同时还能够对Excel做各种操作,下面主要介绍下如何使用PHPExcel进行Excel 2007格式(.xlsx)文件的

POI操纵EXCEL文档之导入文档(一)

             当前主流的后台管理系统,相信都会有文档导入导出的功能.而这其中用到的技术又是多种多样,有用POI框架,也有用JXLS技术的.技术只是手段,项目中实现功能最重要.今天主要说下如何利用POI技术操作EXCEL文档. POI 导入EXCEL文档: 1,首先,要导入EXCEL 文档,就必须要先有导入的模板文件,在这里,我提供好了制作好的EXCEL 模板文件提供下载:( EXCEL文档模板示例下载 ) 2,有了EXCEL 模板文件,就开始编写页面,并编写后台逻辑代码了: <%--

Python3正则表达式清洗Excel文档

本项目中虽然数据量不大,用Excel自带的替换功能也能实现,但是针对上几千条字段去匹配数据的话,Python就明显高效的多,现在开始讲解: 要清洗的是Excel文档中所有字段的地名, 需要清洗数据: 首先,需要导入xlrd和re包,前者是用来读写Excel文档,后者是正则表达式的包 1 #-*- coding:gbk -*- 2 import xlrd 3 import re 4 5 #打开一个Excel表 6 data = xlrd.open_workbook('/home/kin/compa

EXCEL基础内容学习笔记(二)Excel文档的基本组成与功能介绍

一.基本组成 (一)工作簿.工作表与单元格 (1)工作簿:一个Excel文档即为一个工作簿. (2)工作表:工作簿中的每个表. (3)单元格:打开Excel文档,在工作表中单击,出现的加粗四边形即为单元格.单元格由行和列组成,命名时由行和列说明,称为单元格名称或地址. 一个工作簿中有若干个工作表,每个工作表有许多单元格组成. 二.功能介绍 (1)标题栏:Excel文档最上端. (2)选项卡 (3)工作区:每一个打开的选项卡都含有若干工作区. (4)名称框:所选择的单元格的名字. (5)编辑栏:可

mac OS X:将CSV格式转换为Excel文档格式

一:在Mac上如果你使用Excel打开windows导出的CSV格式文档,你会发现表格中所有的的内容都显示在A列.那么,如何恢复正常呢,你可以将CSV格式的文档导入到Excel文档中,这样就正常显示了. 1. 2. 3. 4. 5. 6. 7. 8. 9. 二:中文乱码解决方法 使用 Numbers软件打开文档,然后 ps: 其实可以不用Excel的,直接使用Numbers就足够了,编辑和导出. 版权声明:本文为博主原创文章,未经博主允许不得转载.

php用PHPExcel库生成Excel文档的例子

<?php require_once '../libs/PHPWord/PHPWord.php'; require_once '../libs/PHPWord/PHPWord/IOFactory.php'; require_once '../../config.php'; // New Word Document $PHPWord = new PHPWord(); $objExcel->getProperties()->setCreator("office 2003 excel