vba 使用 C# 在 Excel 中复制/粘贴单元格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45294597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy/paste cells in Excel with C#
提问by Arnold_john
How to select a specific user range in Excel file and copy those cells and Insert copied cells Shift:=xlDown
using C#.
如何在 Excel 文件中选择特定用户范围并Shift:=xlDown
使用 C#复制这些单元格和插入复制的单元格。
This is the VBA code I need to convert into C#:
这是我需要转换为 C# 的 VBA 代码:
Range("A9:L9").Select
Selection.Copy
Rows("10:10").Select
Selection.Insert Shift:=xlDown
Range("F10").Select
I don't know how to convert this code into C# code to run.
我不知道如何将这段代码转换成 C# 代码来运行。
回答by Starlord Live
If you have'nt tried this yet, then you can try this
如果你还没有尝试过这个,那么你可以试试这个
Add reference to your project in VS
: Microsoft.Office.Interop.Excel
添加对您的项目的引用VS
:Microsoft.Office.Interop.Excel
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
var excelapp = new Excel.Application();
excelapp.Workbooks.Add();
string path = "Your Excel Path";
Excel.Workbook workbook = excelapp.Workbooks.Open(path);
Excel.Worksheet workSheet = workbook.Worksheets.get_Item(1);
Excel.Range source = workSheet.Range["A9:L9"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Excel.Range dest = workSheet.Range["F10"];
source.Copy(dest);
}
}
回答by Arnold_john
Excel.Application excelapp = new Excel.Application();
excelapp.Workbooks.Add();
string path = @"Z:\Excel operation\TestExcel\hi.xlsx";
Excel.Workbook workbook = excelapp.Workbooks.Open(path);
Excel.Worksheet workSheet = workbook.Worksheets.get_Item(1);
workSheet.Range["A9:L9"].Copy(workSheet.Range["A10:L10"]);
workSheet.Range["A10:L10"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
excelapp.Visible = true;
var source = workSheet.Range["A9:L9"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Excel.Range dest = workSheet.Range["A10:L10"];
workSheet.Range["A9:L9"].Copy(dest);
excelapp.ActiveWorkbook.Save();
excelapp.Visible = true;
回答by Programming with Mark
Using EPPlus- one of the best C# open-source libraries for Excel - you can do the following
使用EPPlus- Excel 最好的 C# 开源库之一 - 您可以执行以下操作
var fileName = new FileInfo(@"C:\Temp\sample101.xlsx");
//lets open the copy
using (var excelFile = new ExcelPackage(fileName))
{
// select 1st worksheet
var worksheet = excelFile.Workbook.Worksheets[0];
// copy from A9:L9
var cellRange = worksheet.Cells["A9:L9"];
// copy to destination A10:L10
var destination = worksheet.Cells["A10:L10"];
cellRange.Copy(destination);
// save file
excelFile.Save();
}
You can install EPPlus using Nuget by running the following command in the NuGet Package Manager console.
您可以通过在 NuGet 包管理器控制台中运行以下命令来使用 Nuget 安装 EPPlus。
Install-Package EPPlus