我有一个 Windows 窗体应用程序,其中用户将他们的姓名(名字和姓氏)输入到组合框中。我有一个添加按钮,可以将他们输入的任何值添加到组合框中并在下面列出。我想要做的是获取组合框中列出的名称并将它们输入到 Excel 中的单独行中。我在 excel 文件中也有 2 列“名字”和“姓氏”,因此组合框中的名称需要拆分。
这是我的excel代码:
if (!File.Exists(@"C:\gradsheet.xlsx"))
{
File.WriteAllBytes(@"C:\gradesheet.xlsx", Properties.Resources.gradesheet);
}
// if there is no title selected
if (String.IsNullOrEmpty(cboSelect.Text))
{
MessageBox.Show("Please make sure a category is selected.", "No Subject Found Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
object oOpt = System.Reflection.Missing.Value;
Excel.Application excelApp = new Excel.ApplicationClass();
Excel.Workbook wBook;
string myPath = @"C:\gradesheet.xlsx";
wBook = excelApp.Workbooks.Open(myPath, Missing.Value, Missing.Value,
Missing.Value, Missing.Value,
Missing.Value, Missing.Value,
Missing.Value, Missing.Value,
Missing.Value, Missing.Value,
Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
Excel.Worksheet wSheet = (Excel.Worksheet)wBook.Worksheets[1];
wBook.Worksheets.get_Item(1);//get worksheet number
wSheet.Name = cboSelect.Text;//define name
//put name in excel(THIS IS WHERE I NEED THE COMBOBOX ITEMS IN EXCEL)
excelApp.Cells[8, 1] = firstName;
excelApp.Cells[8, 2] = lastName;
//Subject Name to cell
excelApp.Cells[5, 1] = cboSelect.Text;
//these are some cleanup calls that I found in another example..
excelApp.AlertBeforeOverwriting = false;
excelApp.DisplayAlerts = false;
excelApp.Save();
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
DialogResult result;
result = MessageBox.Show("Would you like to open the gradesheet?", "gradesheet", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
string gradesheet = @"C:\gradesheet.xlsx";
Process.Start(gradesheet);
}
}
这是我将名字和姓氏分开的代码,但我不确定如何为组合框中的每个项目执行此操作:
string fullName = cboStudent.Text;
string firstName;
string lastName;
string[] parts = fullName.Split(new string[] { ", " }, StringSplitOptions.None);
if (parts.Length == 1)
{
parts = fullName.Split(' ');
if (parts.Length == 1)
{
lastName = fullName;
firstName = "";
}
else
{
lastName = parts[1];
firstName = parts[0];
}
}
else
{
lastName = parts[0];
firstName = parts[1];
}