简体   繁体   中英

How to add an Object as an Excel row using C#

I have a class say for instance - Member which looks like

class Member
{
    public string Id { get; set; }
    public string Login { get; set; }
    public string AddDate { get; set; }
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public string FullName { get; set; }            
}

Now I need to insert and Object of Member as a Row into an Excel sheet. I am using Microsoft.Office.Interop and have a WorkSheet object by using the code below:

Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets[1];

My final output should look like 在此处输入图片说明

Well you've already declared your Excel.Worksheet , now you just need to iterate over your Member classes that are stored somewhere and write each of their properties into the worksheet.

Assuming you have all Member classes stored in a List<Member> members and all header values in a List<string> headers :

//Setting up headers

int column = 1;
foreach (var item in members)
    xlWorksheet.Cells[1, column++].Value = item;

//setting up member values

int row = 2;
foreach (var item in members)
{
    column = 1;
    xlWorksheet.Cells[row, column++].Value = item.Id;
    xlWorksheet.Cells[row, column++].Value = item.Login;
    xlWorksheet.Cells[row, column++].Value = item.AddDate;
    xlWorksheet.Cells[row, column++].Value = item.FirstName;
    xlWorksheet.Cells[row, column++].Value = item.LastName;
    xlWorksheet.Cells[row++, column].Value = item.FullName;
}

Please note that this might not be the optimal solution if you're dealing with crazy big amounts of data that needs to be inserted into the worksheet. In that case you could disable excel's screenupdating ( xlApp.ScreenUpdating = false; ), however, please note that you should enable it back to true after you're done with your insertion. I think in your case the simplicity of my code will work just fine, but if you absolutely must optimize it, then you could also insert an array of Member directly by using Value2 of the Excel.Range . Something like this:

const int rowCount = 1, columnCount = 6;
object[,] membersArray = new object[rowCount, columnCount];
//fill up membersArray with your data here
xlWorksheet.Cells[1, 1].Value2 = membersArray;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM