如何使用C#将对象添加为Excel行

时间:2016-03-04 17:24:53

标签: c# excel winforms excel-interop

我有一个班级说 - 例如

的成员
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; }            
}

现在我需要将“成员对象”作为一行插入到Excel工作表中。我正在使用Microsoft.Office.Interop并使用以下代码获得WorkSheet对象:

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

我的最终输出应该是这样的 enter image description here

1 个答案:

答案 0 :(得分:2)

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;