ListBox to Excel
Ok, so I have a class, customer, that I use to process data, and then add to a list box, like below:
//Submit data from current form
customer aCustomer = new customer(comboBox1.Text, textBox1.Text, ChannelSelecBox.Text,
PurchaserTextBox.Text, NameTextBox.Text, emailTextBox.Text, AddressTextBox.Text, StateBox.Text,
PayMethodDropDown.Text, Prod1Num.Value.ToString(), Prod2Num.Value.ToString(),
Prod3Num.Value.ToString(), Prod4Num.Value.ToString(), Prod5Num.Value.ToString(),
Prod6Num.Value.ToString(), SubTData.Text, DiscountTextBox.Text, TaxData.Text, CommentTextBox.Text,
ShipData.Text, TotalData.Text);
// Add aCustomer to ListBox
Orders.Items.Add(aCustomer);
I have a string override so that the listbox just displays the purchaser and the date. Now I want to take all the orders entered into the list box and put, most of, this data into an excel spreadsheet, eac开发者_JAVA百科h into it's own column. How could I do this?
If you need more information or to see more of my code, let me know.
try the following;
object oOpt = System.Reflection.Missing.Value; //for optional arguments
Excel.Application oXL = new Excel.Application();
Excel.Workbooks oWBs = oXL.Workbooks;
Excel.Workbook oWB = oWBs.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet oSheet = (Excel.Worksheet)oWB.ActiveSheet;
//outputRows is a List<List<object>>
int numberOfRows = outputRows.Count;
int numberOfColumns = outputRows.Max(list => list.Count);
Excel.Range oRng =
oSheet.get_Range("A1", oOpt)
.get_Resize(numberOfRows, numberOfColumns);
object[,] outputArray = new object[numberOfRows, numberOfColumns];
for (int row = 0; row < numberOfRows; row++)
{
for (int col = 0; col < outputRows[row].Count; col++)
{
outputArray[row, col] = outputRows[row][col];
}
}
oRng.set_Value(oOpt, outputArray);
oXL.Visible = true;
more details can be found at http://csharp.net-informations.com/excel/csharp-create-excel.htm
Use CSV as file format, not XLS. Excel is a pain. Especially when reading from XLS. Some incorrect cell formatting and you sometimes get the value, but sometimes not. Even in same file. Personal experience.
精彩评论