hameedmd
hameedmd

Reputation: 3

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. I am having trouble specifying the c# code to look for data in a specified column that isn't the first column. The excel worksheet contains data about employees details such as name, number, department and email. I want the code to search the column and for the data that matches a certain position e.g. 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. 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.

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.

Upvotes: 0

Views: 1004

Answers (1)

sin2akshay
sin2akshay

Reputation: 333

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.

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.

| Name | Number | Department  | Email   | Position  |
|------|--------|-------------|---------|-----------|
| A    | 1      | DepartmentA | [email protected] | Permanent |
| B    | 2      | DepartmentB | [email protected] | Trainee   |
| C    | 3      | DepartmentB | [email protected] | Trainee   |

Using OleDB to get Excel Data:

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. 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. There are many ways to do that, you can check other questions on SO. Example

You can also use ClosedXML. It is quite easy to work with Excels.

Upvotes: 1

Related Questions