利用C#语言编写服务要求将某个文件夹下面的Excel复制到另一个硬盘某个文件夹下面并根据Excel的名字创建不同的文件夹将Excel存储到对应的文件夹下面每次运行时只复制新产出的Excel
您可以使用以下代码来实现您的需求:
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelCopyService
{
class Program
{
static void Main(string[] args)
{
string sourceFolderPath = @"C:\SourceFolder";
string destinationFolderPath = @"D:\DestinationFolder";
// Get the list of Excel files in the source folder
string[] excelFiles = Directory.GetFiles(sourceFolderPath, "*.xlsx");
foreach (string excelFile in excelFiles)
{
string fileName = Path.GetFileNameWithoutExtension(excelFile);
string destinationPath = Path.Combine(destinationFolderPath, fileName);
// Only copy the file if the destination folder does not exist already
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
File.Copy(excelFile, Path.Combine(destinationPath, Path.GetFileName(excelFile)));
Console.WriteLine($"Copied {excelFile} to {destinationPath}");
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
请确保您的项目引用了 Microsoft.Office.Interop.Excel 组件。如果未引用,请使用以下步骤:
- 在 Visual Studio 中,右键单击项目,选择“管理 NuGet 程序包”。
- 在“NuGet 程序包管理器”窗口中,搜索 Microsoft.Office.Interop.Excel。
- 选择 Microsoft.Office.Interop.Excel,并点击“安装”按钮以引用它。
此代码将遍历源文件夹中的所有 Excel 文件,并将它们复制到目标文件夹中的适当文件夹中。只有当目标文件夹不存在时才会进行复制,以避免重复复制已存在的文件
原文地址: https://www.cveoy.top/t/topic/h8wT 著作权归作者所有。请勿转载和采集!