Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我的程序需要很多时间来更改Excel文件_C#_Excel - Fatal编程技术网

C# 我的程序需要很多时间来更改Excel文件

C# 我的程序需要很多时间来更改Excel文件,c#,excel,C#,Excel,我用c#打开excel文件,进行更改并保存后,但我有一个问题,我的程序需要花费很多时间来完成这项工作。我能做什么 我怎样才能更快地完成我的计划 我把代码放在这里: 我有一个文件Form1.c: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Tex

我用c#打开excel文件,进行更改并保存后,但我有一个问题,我的程序需要花费很多时间来完成这项工作。我能做什么

我怎样才能更快地完成我的计划

我把代码放在这里:

我有一个文件Form1.c:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using RutaExcel;
using System.Runtime.InteropServices;

namespace Excel_Path
{
    public partial class Form1 : Form
    {
        static string pathOut = null;
        static string pathLogOut = null;
        static string pathOrigen = null;
        static string NameLog = null;
        [DllImport("kernel32.dll")]
        public static extern Boolean AllocConsole();
        [DllImport("kernel32.dll")]
        public static extern Boolean FreeConsole();

        public Form1()
        {
            InitializeComponent();
            AllocConsole();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void folderBrowserDialog2_HelpRequest(object sender, EventArgs e)
        {

        }

        private void maskedTextBox2_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
        {

        }

        private void maskedTextBox2_Click(object sender, EventArgs e)
        {
            folderBrowserDialog2.ShowDialog();
            maskedTextBox2.Text = folderBrowserDialog2.SelectedPath;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Agafem les rutes per copiar els fitxers d'excel
            pathOrigen = maskedTextBox2.Text;
            pathOut = @"C:\";
            string[] words = pathOrigen.Split('\\');
            int LengthWord = words.Length;
            NameLog = words[LengthWord - 1];
            pathLogOut = pathOut + NameLog + ".txt";

            // This text is added only once to the file.
            if (File.Exists(pathLogOut))
            {
                File.Delete(pathLogOut);
            }
            if (Directory.Exists(pathOut))
            {
                // Create a file to write to.
                using (StreamWriter sw = File.CreateText(pathLogOut))
                {
                    sw.WriteLine("Ficheros que se han pasado correctamente");
                    sw.WriteLine();
                }
                RutaExcel.Program.DirSearch(pathOrigen, pathOut, pathLogOut);
                RutaExcel.Program.FileSearch(pathOrigen, pathOut, pathLogOut);
                using (StreamWriter sw = File.AppendText(pathLogOut))
                {
                    sw.WriteLine();
                    sw.WriteLine("Proceso de guardado finalizado");
                }
                Console.WriteLine("¡Hecho!");
                Console.ReadLine();
                FreeConsole();
            }
        }
    }
}
和第二个文件Main.c

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;
using VBA = Microsoft.Vbe.Interop;

namespace RutaExcel
{
    public class Program
    {
        static int IndexFile = 0;

        static void Main(string[] args)
        {

        }

        public static void read_file(string file, string dir, string pathOut, string pathLogOut)
        {
            //Antes de nada, miramos el formato que tiene el fichero que nos entra. Si el fichero en cuestion no tiene ninguna extension de excel,
            //no hacemos nada.
            string[] words = file.Split('.');
            int LengthWord = words.Length;
            string fileFormat = words[LengthWord - 1];
            //Verificamos el formato que tiene el fichero de entrada. Si es excel seguimos con el proceso.
            if (fileFormat == "XLS" || fileFormat == "xls" || fileFormat == "XLSX" || fileFormat == "xlsx" || fileFormat == "XLSM" || fileFormat == "xlsm" ||
               fileFormat == "XLSB" || fileFormat == "xlsb" || fileFormat == "XLT" || fileFormat == "xlt" || fileFormat == "XLA" || fileFormat == "xla")
            {
                try
                {
                    if (!File.Exists(file))
                        return;

                    //Path para el fichero destino
                    string fileDestiny = file.Replace(@"IN\", "");
                    Console.WriteLine(fileDestiny);
                    //Si el fichero ya exisita lo borramos para no crear ficheros corruptos
                    if (File.Exists(fileDestiny))
                    {
                        File.SetAttributes(fileDestiny, FileAttributes.Normal);
                        File.Delete(fileDestiny);
                    }

                    DirectoryInfo di = new DirectoryInfo(fileDestiny);
                    try
                    {
                        // Determine whether the directory exists.
                        if (di.Exists)
                        {
                            // Indicate that the directory already exists.
                            Console.WriteLine("That path exists already.");
                            return;
                        }
                        // Try to create the directory.
                        di.Create();
                        Console.WriteLine("The directory was created successfully.");

                        // Delete the directory. Sirve para eliminar el acceso a ese directorio.
                        di.Delete();
                        Console.WriteLine("The directory was deleted successfully.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("The process failed: {0}", e.ToString());
                    }

                    //Copio el fichero original en otro directorio. Si el fichero original tiene permisos de solo lectura, la copia que hago tambien los tendra.
                    //Así pues, lo que haremos sera quitarle dichos permisos a la copia para poder modificar el contenido y despues, al acabar dicho proceso,
                    //volveremos a poner los permisos corresponientes a la copia modificada.
                    System.IO.File.Copy(file, fileDestiny, true);
                    FileAttributes attributes = File.GetAttributes(fileDestiny);
                    File.SetAttributes(fileDestiny, FileAttributes.Normal);

                    Excel.Application xlApp;
                    Excel.Workbook xlWorkBook = null;
                    Excel.Range range = null;

                    var misValue = Type.Missing;//System.Reflection.Missing.Value;

                    // abrir el documento
                    xlApp = new Excel.Application();
                    xlApp.DisplayAlerts = false;
                    xlWorkBook = xlApp.Workbooks.Open(fileDestiny, misValue, misValue,
                        misValue, misValue, misValue, misValue, misValue, misValue,
                        misValue, misValue, misValue, misValue, misValue, misValue);

                    //Si el excel contiene macros creadas a partir de Visual Basic, exportamos las macros al nuevo fichero destino.
                    //Al exportar dichas macros, se crean unos ficheros con extension .bas dentro del directorio donde nos situamos.
                    //Una vez tenemos los ficheros exportados, estos los sobreescribimos con los cambios pertinentes.
                    //Una vez hecho todo esto, borramos los archivos .bas que se han ido creando en la carpeta origen.
                    VBA.VBProject project = xlWorkBook.VBProject;
                    VBA.VBComponents VBComponents = project.VBComponents;
                    string filePath = null;
                    foreach (VBA.VBComponent Component in VBComponents)
                    {
                        if (Component.Type == VBA.vbext_ComponentType.vbext_ct_StdModule)
                        {
                            Component.Export(pathOut + Component.Name + ".bas");
                            filePath = pathOut + Component.Name + ".bas";

                            StreamReader reader = new StreamReader(filePath, Encoding.Default);
                            string content = reader.ReadToEnd();
                            reader.Close();

                            content = Regex.Replace(content, @"T:\\", @"T:\Gestion\");

                            StreamWriter writer = new StreamWriter(filePath, false, Encoding.Default);
                            writer.Write(content);
                            writer.Close();

                            Component.CodeModule.DeleteLines(1, Component.CodeModule.CountOfLines);
                            Component.CodeModule.AddFromFile(filePath);
                            File.Delete(filePath);
                        }
                    }

                    foreach (Excel.Worksheet sheet in xlWorkBook.Sheets)
                    {
                        // seleccion rango activo
                        range = sheet.UsedRange;
                        // leer las celdas
                        int rows = range.Rows.Count;
                        int cols = range.Columns.Count;
                        for (int row = 1; row <= rows; row++)
                        {
                            for (int col = 1; col <= cols; col++)
                            {
                                if (!(range.Cells[row, col].Value == null))
                                {
                                    string valorBar = range.Cells[row, col].Formula.Replace(@"C:\", @"C:\Gestion\");
                                    range.Cells[row, col].Formula = valorBar;
                                    Console.WriteLine(valorBar);
                                }
                            }
                        }
                        // liberar
                        releaseObject(sheet);
                    }

                    // Guardar y cerrar
                    Excel.XlFileFormat FileFormat = xlWorkBook.FileFormat;
                    xlWorkBook.SaveAs(fileDestiny, FileFormat);
                    xlWorkBook.Close();

                    //Volvemos a poner los permisos predeterminados que tenia el fichero copiado de excel.
                    File.SetAttributes(fileDestiny, attributes);

                    // liberar
                    releaseObject(xlWorkBook);
                    releaseObject(xlApp);
                    //Escribir en un archivo, los ficheros que se han ido pasando.
                    IndexFile = IndexFile + 1;
                    using (StreamWriter sw = File.AppendText(pathLogOut))
                    {
                        sw.WriteLine(IndexFile + "." + file + " --> Hecho");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("El fichero {0} no se ha guardado correctamente! {1}", file, e.ToString());
                }
            }
        }

        public static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to release the object(object:{0})", obj.ToString());
            }
            finally
            {
                obj = null;
                GC.Collect();
            }
        }

        public static void DirSearch(string sDir, string pathOut, string pathLogOut)
        {
            try
            {
                string[] DirectoryEntries = Directory.GetDirectories(sDir);
                foreach (string d in DirectoryEntries)
                {
                    foreach (string f in Directory.GetFiles(d))
                    {
                        read_file(f, d, pathOut, pathLogOut);
                    }
                    DirSearch(d, pathOut, pathLogOut);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
        }

        public static void FileSearch(string d, string pathOut, string pathLogOut)
        {
            try
            {
                string[] FilesEntries = Directory.GetFiles(d);
                foreach (string f in FilesEntries)
                {
                    read_file(f, d, pathOut, pathLogOut);
                }
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.IO;
使用System.Text.RegularExpressions;
使用Excel=Microsoft.Office.Interop.Excel;
使用VBA=Microsoft.Vbe.Interop;
名称空间RutaExcel
{
公共课程
{
静态int IndexFile=0;
静态void Main(字符串[]参数)
{
}
公共静态无效读取文件(字符串文件、字符串目录、字符串路径输出、字符串路径注销)
{
//在这一点上,米拉莫斯·艾尔菲舍罗的形式是一种新的形式,而不是一种新的形式,
//没有hacemos nada。
string[]words=file.Split('.');
int LengthWord=单词长度;
字符串文件格式=字[纵向-1];
//验证数据的格式。这是一个卓越的过程。
如果(fileFormat==“XLS”| | fileFormat==“XLS”| | fileFormat==“XLSX”| | fileFormat==“XLSX”| | fileFormat==“XLSM”| fileFormat==“XLSM”||
fileFormat==“XLSB”| | fileFormat==“XLSB”| | fileFormat==“XLT”| | fileFormat==“XLT”| | fileFormat==“XLA”| fileFormat==“XLA”)
{
尝试
{
如果(!File.Exists(File))
回来
//菲希罗路
字符串fileDestiny=file.Replace(@“IN\”,“”);
Console.WriteLine(fileDestiny);
//这是一个存在于博拉莫斯(borramos)的无名小卒
if(File.Exists(fileDestiny))
{
SetAttributes(fileDestiny,FileAttributes.Normal);
File.Delete(fileDestiny);
}
DirectoryInfo di=新的DirectoryInfo(fileDestiny);
尝试
{
//确定目录是否存在。
如果(di.存在)
{
//指示目录已存在。
WriteLine(“该路径已经存在。”);
回来
}
//尝试创建目录。
di.Create();
WriteLine(“目录已成功创建”);
//删除目录。Sirve para eliminar el acceso a ese directorio。
di.Delete();
WriteLine(“目录已成功删除”);
}
捕获(例外e)
{
WriteLine(“进程失败:{0}”,e.ToString());
}
//首席执行官。首席执行官是首席执行官。首席执行官是首席执行官。
//正如我所说的那样,我们需要一种新的方法来改变当前和未来的局面,一种新的方法,
//一个许可证对应一个修改副本。
System.IO.File.Copy(File,fileDestiny,true);
FileAttributes=File.GetAttributes(fileDestiny);
SetAttributes(fileDestiny,FileAttributes.Normal);
Excel.applicationxlapp;
Excel.Workbook xlWorkBook=null;
Excel.Range=null;
var misValue=Type.Missing;//System.Reflection.Missing.Value;
//阿布里尔·艾尔·德克托
xlApp=new Excel.Application();
xlApp.DisplayAlerts=false;
xlWorkBook=xlApp.Workbooks.Open(fileDestiny、misValue、misValue、,
误判,误判,误判,误判,误判,误判,
错误价值,错误价值,错误价值,错误价值,错误价值,错误价值,错误价值);
//将excel宏作为Visual Basic的一部分,导出新的宏。
//这是一个巨大的出口,它是一个非政府组织的延伸,是一个新的发展方向。
//我们的出口是菲舍罗,出口是柬埔寨。
//我们要做的是,我们要做的是建筑。我们要做的是地毯上的装饰。
VBA.VBProject项目=xlWorkBook.VBProject;
VBA.VBComponents VBComponents=project.VBComponents;
字符串filePath=null;
foreach(VBA.VBComponent组件中的VBA.VBComponent组件)
{
if(Component.Type==VBA.vbext\u ComponentType.vbext\u ct\u标准模块)
{
Component.Export(pathOut+Component.Name+“.bas”);
filePath=pathOut+Component.Name+“.bas”;
StreamReader=新的StreamReader(filePath,Encoding.Default);
字符串内容=reader.ReadToEnd();
reader.Close();
content=Regex.Replace(content,@“T:\\”,@“T:\Gestion\”;
StreamWriter writer=新StreamWriter(文件路径,false,Encoding.Default);
作者:写(内容);
 range = sheet.UsedRange;
                    // leer las celdas
                    int rows = range.Rows.Count;
                    int cols = range.Columns.Count;
                    for (int row = 1; row <= rows; row++)
                    {
                        for (int col = 1; col <= cols; col++)
                        {
                            if (!(range.Cells[row, col].Value == null))
                            {
                                string valorBar = range.Cells[row, col].Formula.Replace(@"C:\", @"C:\Gestion\");
                                range.Cells[row, col].Formula = valorBar;
                                Console.WriteLine(valorBar);
                            }
                        }
                    }
 range = sheet.UsedRange;
 // leer las celdas
 int rows = range.Rows.Count;
 int cols = range.Columns.Count;

 var startCell = (Range)WorkSheet.Cells[1, 1];
 var endCell = (Range)WorkSheet.Cells[rows, cols];
 var range = WorkSheet.Range[startCell, endCell];

 range.Formula.Replace(@"C:\", @"C:\Gestion\");
 range.Formula = valorBar;