2014-02-10 42 views
-2

我用c#打开excel文件,我做了更改并保存后,但是我遇到了问题,我的程序需要很多时间才能执行此操作。我可以做什么 ?我的程序需要花费很多时间来更改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); 
      } 
     } 
    } 
} 

谢谢!

+0

的第一件事是分享您的代码! –

+0

包含您的代码,以便其他开发人员可以查看可能出错的位置。简单地粘贴这个问题没有足够的细节只会让它被拒绝。 –

+5

对于每个性能问题都没有适用的魔术技巧。分享您的代码 – OuSs

回答

0

我不知道这是否会工作,因为我没有你的Excel文件,但

一件事你可以做的是在同一时间创造一个更大的范围,而不是一个细胞。

对于此代码 - 它看起来像你走了每一行和每列以取代C:\C:\Gestion

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; 
+0

那么,范围是声明在上面,但你在这里再次声明: –

+0

那么,变量范围是在这个程序的顶部声明,但你在这里再次声明var range = WorkSheet.Range [startCell,endCell]; 所以,在你的代码中的变量valorBar是没有什么 –

+0

我尝试这段代码,但它不能很好地工作。你能帮我吗 ?谢谢! –

相关问题