我开发“Excel 2007 插件”并使用“Microsoft.Office.Interop.Excel.Application.ActiveSheet”。如何将其保存在单独的文件中?
问问题
3079 次
3 回答
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);
}
}
}
于 2012-09-11T11:30:51.490 回答
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();
}
}
于 2012-09-11T11:16:08.433 回答
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);
}
}
}
于 2019-08-28T14:42:55.867 回答