我编写了代码来读取 excel 文件。当我添加联系人值时,我需要将这些值写入 excel 文件,但问题是这些值无法写入 excel 文件中的单元格。空白的!!!!为什么?我的代码有什么问题?
static void Main(string[] args)
{
var contacts = new List<Contact>();
contacts.Add(new Contact{Firstname = "name 1", Lastname = "lastname 1", Email = "email 1", PhoneNumber = "phone 1"});
contacts.Add(new Contact { Firstname = "name 2", Lastname = "lastname 2", Email = "email 2", PhoneNumber = "phone 2" });
Application app = new Application();
// excelapp.Visible = true;
// _Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));
Workbook workbook = app.Workbooks.Open(@"N:\files\transform_results.xlsx");
_Worksheet worksheet = workbook.Sheets["Sheet1"];
Range xlRange = worksheet.UsedRange;
worksheet = (_Worksheet)workbook.ActiveSheet;
worksheet.Cells[1, 1] = "First Name";
worksheet.Cells[1, 2] = "Last Name";
worksheet.Cells[1, 3] = "Email";
int row = 4;
foreach (var contact in contacts)
{
worksheet.Cells[1, 1] = contact.Firstname;
worksheet.Cells[1, 2] = contact.Lastname;
worksheet.Cells[1, 3] = contact.Email;
worksheet.Cells[1, 4] = contact.PhoneNumber;
}
app.UserControl = true;
}
public class Contact
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
}