简体   繁体   English

如何使用C#将一个Excel工作簿中特定范围的单元格复制到另一工作簿中

[英]how to copy cells from a specific range from one excel workbook to another workbook using c#

I need help to copy some data from cells in one excel workbook to another excel workbook. 我需要帮助将某些数据从一个Excel工作簿中的单元格复制到另一个Excel工作簿中。 I am having trouble specifying the c# code to look for data in a specified column that isn't the first column. 我在指定c#代码以查找不是第一列的指定列中的数据时遇到麻烦。 The excel worksheet contains data about employees details such as name, number, department and email. excel工作表包含有关员工详细信息的数据,例如姓名,电话号码,部门和电子邮件。 I want the code to search the column and for the data that matches a certain position eg trainee instead of permanent. 我希望代码搜索列并查找与某个位置匹配的数据,例如,受训者而不是永久雇员。 The code should be able to copy the people who are trainees and paste in another specified workbook. 该代码应能够复制受训人员并粘贴到另一个指定的工作簿中。

I have tried to implement an if statement and if the cell contains the string 'trainee' it will paste the data into another workbook, this was successful only when the column was the first, which in the actual spreadsheet it wasn't. 我尝试实现一个if语句,如果该单元格包含字符串'trainee',它将把数据粘贴到另一个工作簿中,只有当该列是第一列时才成功,而在实际电子表格中则不是。 I have searched all over the internet but can't find a conclusive tutorial on how to manipulate excel with c# in a console app . 我在互联网上进行了搜索,但是找不到关于如何在控制台应用程序中使用c#操纵excel的结论性教程。

using Excel = Microsoft.Office.Interop.Excel;
class Program
{
     static void Main(string[] args)
    {
        var excelapp = new Excel.Application();
        excelapp.Workbooks.Add();
        string path = 
@"C:\Users\....xlsx";
        Excel.Workbook workbook = excelapp.Workbooks.Open(path);
        Excel.Worksheet workSheet = workbook.Worksheets.get_Item(1);
        var source = 
  workSheet.Range["h3:H10"].Insert(Excel.XlInsertShiftDirection.xlShiftDown);
        Excel.Range dest = workSheet.Range["F10"];
        workbook.SaveAs("Book1.xlsx");
    }
}

This current code will only copy the entire spreadsheet and paste into a new workbook. 当前代码仅复制整个电子表格并将其粘贴到新工作簿中。 I only want the relevant data. 我只想要相关数据。

Interop code is a bit difficult to understand and work with. 互操作代码有点难以理解和使用。 I would suggest you to either use OleDb or some OpenXML alternative for working with Excel files. 我建议您使用OleDb或一些OpenXML替代方法来处理Excel文件。

From what I understood from your question is that the table looks something like this in excel and you want to copy rows having Position as 'Trainee' into a new WorkSheet. 据我所知,您的问题是表格在excel中看起来像这样,您想将具有“ Trainee”作为“职位”的行复制到新的WorkSheet中。

| Name | Number | Department  | Email   | Position  |
|------|--------|-------------|---------|-----------|
| A    | 1      | DepartmentA | A@a.com | Permanent |
| B    | 2      | DepartmentB | B@b.com | Trainee   |
| C    | 3      | DepartmentB | C@c.com | Trainee   |

Using OleDB to get Excel Data: 使用OleDB获取Excel数据:

var conStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties='Excel 12.0;HDR={1};IMEX=1'";
var pathToExcel = @"C:\Users\....xlsx";;
var udt = new DataTable();
conStr = string.Format(conStr, pathToExcel, "Yes");
using (var connExcel = new OleDbConnection(conStr))
{
    var cmdExcel = new OleDbCommand();
    var oda = new OleDbDataAdapter();

    connExcel.Open();
    var dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    if (dtExcelSchema != null)
    {
        //Get the name of First Sheet
        var sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();


        cmdExcel.Connection = connExcel;
        cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
    }
    oda.SelectCommand = cmdExcel;
    oda.Fill(udt);
}

We put the data fetched from Excel to a datatable. 我们将从Excel获取的数据放入数据表中。 Then you can just write a simple query to fetch whatever data you want, 然后,您可以编写一个简单的查询来获取所需的任何数据,

//Getting array of DataRow with required data
var rows = udt.Select("[Position]='Trainee');
if (rows.Length > 0)
    DataTable finalDataTable = rows.CopyToDataTable();

Then you can convert DataTable to another WorkSheet or Excel sheet as required. 然后,您可以根据需要将DataTable转换为另一个WorkSheet或Excel工作表。 There are many ways to do that, you can check other questions on SO. 有很多方法可以做到这一点,您可以在SO上检查其他问题。 Example

You can also use ClosedXML . 您也可以使用ClosedXML It is quite easy to work with Excels. 使用Excel非常容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C# - 如何将单个 Excel 工作表从一个工作簿复制到另一个工作簿? - C# - How to copy a single Excel worksheet from one workbook to another? 使用c#将一个或多个单元格的内容从workBook1中的一个工作表复制到workbook2中的另一个现有工作表 - Copy contents of cell/cells from one sheet in workBook1 to the other existing sheet in workbook2 using c# c#-(Excel互操作)如何在VSTO中将一个工作表复制到另一工作簿? - c# - (Excel interop)How can I copy one worksheet to another workbook in VSTO? 如何将特定单元格(带有值、颜色、字体)从一个 excel 文件复制到另一个 excel 文件 C#? - How can I copy specific cells(with Value,Color,Font) from one excel file to another excel file C#? 在C#中运行Excel宏在特定工作簿中失败 - Running Excel macro in a specific workbook fails from C# 如何在C#中将两个Excel工作簿合并为一个工作簿? - How to merge two Excel workbook into one workbook in C#? 将Excel DropDown从WorkBook复制到新工作簿 - Copy Excel DropDown from WorkBook to a new Workbook 使用SpreadsheetGear从一个工作簿粘贴到另一个工作簿 - Pastespecial Range from one workbook to another using SpreadsheetGear 如何将Excel工作表从工作簿A复制到工作簿B - How to copy an excel sheet from workbook A to workbook B 通过C#运行Excel宏:从另一个工作簿运行宏? - Running an Excel Macro via C#: Run a macro from one workbook on another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM