【问题标题】:Perform excel macro on a csv file from C#从 C# 对 csv 文件执行 excel 宏
【发布时间】:2015-11-05 19:10:50
【问题描述】:

我需要使用 C# 在现有的 csv 文件上执行现有的 Excel 宏(用 VB 编写,可以使用宏编辑器从 Excel 复制)。我已经有了可用于在 xlsm 文件上执行宏的工作代码,如下所示:

using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace MacroBuddy
{
    public class test
    {
        public static void go_Macro()
        {
            object oMissing = System.Reflection.Missing.Value;

            //create new Excel application instance
            Excel.Application oExcel = new Excel.Application();

            oExcel.Visible = true;

            Excel.Workbooks oBooks = oExcel.Workbooks;
            Excel._Workbook oBook = null;

            string path = @"C:\Users\user\Desktop\test.csv";

            //open file located at path
            oBook = oBooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

            //run Macro by referencing file and the name of the Macro
            RunMacro(oExcel, new Object[] { "test.xlsm!TestMacro" });

            //save and close workbook
            oBook.Save();
            oBook.Close(false, oMissing, oMissing);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
            oBook = null;
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
            oBooks = null;
            oExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
            oExcel = null;
            GC.Collect();
        }

        private static void RunMacro(object oApp, object[] oRunArgs)
        { oApp.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null, oApp, oRunArgs); }

        static void Main()
        { go_Macro(); }
    }
}

但是,如果指定的文件是 csv 文件,则它不起作用。所以我需要帮助使类似的代码在 csv 文件上工作,或者将 csv 文件从 C# 转换为 xlsm 文件的自动化过程。

此外,能够将 VB 宏代码作为字符串并能够使用将字符串作为参数或类似过程的方法运行宏也会很有帮助。

【问题讨论】:

    标签: c# excel csv xlsm


    【解决方案1】:

    希望以下 2 个链接可以帮助您打开 csv 文件,然后将其保存为 excel 格式。 所以在那之后你打开excel文件并执行你的任务。

    http://msdn.microsoft.com/en-us/library/c9838808.aspx(打开 CSV) http://msdn.microsoft.com/en-us/library/h1e33e36.aspx(保存excel)。

    【讨论】:

      【解决方案2】:

      我一开始没有写入 csv,而是决定使用以下方式写入包含多张工作表的 .xlsx 文件:

      public class test
      {
          object missing = Type.Missing;
          public test()
          {
              Excel.Application XL = new Excel.Application();
              oXL.Visible = false;
              Excel.Workbook WB = XL.Workbooks.Add(missing);
              Excel.Worksheet Sheet = WB.ActiveSheet as Excel.Worksheet;
              oSheet.Name = "First sheet";
              oSheet.Cells[1, 1] = "Written on first sheet";
              Excel.Worksheet Sheet2 = WB.Sheets.Add(missing, missing, 1, missing) 
                          as Excel.Worksheet;
              Sheet2.Name = "Second sheet";
              Sheet2.Cells[1, 1] = "Written on second sheet";
              string fileName = @"C:\temp\SoSample.xlsx";
              oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
                  missing, missing, missing, missing,
                  Excel.XlSaveAsAccessMode.xlNoChange,
                  missing, missing, missing, missing, missing);
              oWB.Close(missing, missing, missing);
              oXL.UserControl = true;
              oXL.Quit();
          }
      }
      

      然后我使用以下代码创建了工作簿:

      private void button1_Click(object sender, System.EventArgs e)
      {
               Excel.Application oExcel;
               Excel.Workbook oBook;
               VBIDE.VBComponent oModule;
               Office.CommandBar oCommandBar;
               Office.CommandBarButton oCommandBarButton;
               String sCode;
               Object oMissing = System.Reflection.Missing.Value;
               // Create an instance of Excel.
               oExcel = new Excel.Application();
      
               // Add a workbook.
               oBook = oExcel.Workbooks.Add(@"C:\Users\user\Downloads\test.xlsm");
      
               // Create a new VBA code module.
               oModule = oBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
      
               sCode =
               //paste in your macro here, with each line followed by a new line
               "Sub TestMacro()\r\n" +
               "Columns(\"D:D\").Select\r\n" +
               "Selection.Copy\r\n" +
               "Columns(\"F:F\").Select\r\n" +
               "ActiveSheet.Paste\r\n" +
               "Application.CutCopyMode = False\r\n" +
               "ActiveSheet.Range(\"$F$1:$F$542\").RemoveDuplicates Columns:=1, Header:=xlNo\r\n" +
               "Range(\"F1\").Select\r\n" +
               "ActiveCell.FormulaR1C1 = \"Unique Query\"\r\n" +
               "Range(\"F2\").Select\r\n" +
               "End Sub";
               // Add the VBA macro to the new code module.
               oModule.CodeModule.AddFromString(sCode);
      
      
      
               // Make Excel visible to the user.
               oExcel.Visible = true;
               // Set the UserControl property so Excel won't shut down.
               oExcel.UserControl = true;
      
               // Release the variables.
               oModule = null;
               oBook = null;
               oExcel = null;             
               // Collect garbage.
               GC.Collect();
      }
      

      然后我能够运行刚刚使用我最初发布的代码创建的宏。

      【讨论】:

        猜你喜欢
        • 2011-09-08
        • 1970-01-01
        • 1970-01-01
        • 2016-12-17
        • 1970-01-01
        • 2016-07-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多