我开发“Excel 2007加载项”并使用“Microsoft.Office.Interop.Excel.Application.ActiveSheet”。如何将其保存在单独的文件中?
答案 0 :(得分:1)
您需要将活动工作表分配给Microsoft.Office.Interop.Excel.Worksheet
对象,然后只需调用此对象的SaveAs方法:
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Excel.Application ap = new Excel.Application();
Excel.Workbook wb = ap.Workbooks.Open(@"C:\whatever.xlsx");
Excel.Worksheet ws = wb.ActiveSheet;
ws.SaveAs(@"C:\somethingelse.xlsx");
ap.Workbooks.Close();
Marshal.ReleaseComObject(ap);
}
}
}
答案 1 :(得分:0)
我发现帖子解释了如何在VB.NET中保存活动表:
Sub test()
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:="C:\MyFolder\MySubFolder\Test.xls"
ActiveWorkbook.Close
End Sub
但您可以在C#中尝试此逻辑,切换活动工作表并单独保存
这应该将它们保存在单独的工作簿中......
Sub test()
Dim iNoSheets As Integer
Dim i As Integer
iNoSheets = Worksheets.Count
For i = 1 To iNoSheets
Worksheets(i).Activate
ActiveSheet.Copy
ActiveWorkbook.SaveAs Filename:="C:\Test" & i & ".xls"
ActiveWorkbook.Close
Next
End Sub
现在在C#中:
public void SaveSheets()
{
for(int i = 0; i < Worksheets.Count; i++)
{
Worksheets[i].Activate();
ActiveSheet.Copy();
ActiveWorkbook.SaveAs(string.Format(@"C:\sheet{0}.xlsx",i));
ActiveWorkbook.Close();
}
}
答案 2 :(得分:0)
下面的工作C#代码已准备好进行复制和粘贴,并将在给定路径下保存当前活动的Excel工作簿(如果取消注释相应的代码行,则将其名称写入控制台):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Excel.Application objApp;
objApp = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
/*Console.WriteLine(objApp.ActiveWorkbook.Name);
Console.ReadKey(); */
objApp.ActiveWorkbook.SaveAs(@"C:\temp\ExcelTest\Test.xlsx", Excel.XlFileFormat.xlWorkbookDefault);
}
}
}