Reputation: 302
Good day, anyone can help me with this problem, I have a code here that counts number of fruits from Column B to Column AF (31 days) I used switch that would be case 1 to case 31. I want my code to be simple or in a loop. 31 case is just too long. By the way my code work, I just want it be short.
Here's my code
private void button1_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application OfficeExcel;
Microsoft.Office.Interop.Excel._Workbook OfficeWorkBook;
Microsoft.Office.Interop.Excel._Worksheet OfficeSheet;
var dtpMonth = dateTimePicker1.Value.ToString("MMMM");
var dtpYear = dateTimePicker1.Value.Year;
var MonthYear = dtpMonth + " - " + dtpYear;
var dtpDay = dateTimePicker1.Value.Day;
try
{
OfficeExcel = new Microsoft.Office.Interop.Excel.Application();
OfficeExcel.Visible = true;
int appletotal = Convert.ToInt32(lblappletotal.Text);
int bananatotal = Convert.ToInt32(lblbananatotal.Text);
int orangetotal = Convert.ToInt32(lblorangetotal.Text);
int grapestotal = Convert.ToInt32(lblgrapestotal.Text);
switch (dateTimePicker1.Value.Day.ToString())
{
case "1":
OfficeWorkBook = (Microsoft.Office.Interop.Excel._Workbook)(OfficeExcel.Workbooks.Add(""));
OfficeSheet = (Microsoft.Office.Interop.Excel._Worksheet)OfficeWorkBook.ActiveSheet;
OfficeSheet.Cells[3,1] = "apple";
OfficeSheet.Cells[4,1] = "banana";
OfficeSheet.Cells[5,1] = "orange";
OfficeSheet.Cells[6,1] = "grapes";
OfficeSheet.Cells[2, 2] = dtpDay + dtpMonth ;
OfficeSheet.Cells[3, 2] = appletotal; // variable
OfficeSheet.Cells[4, 2] = bananatotal;
OfficeSheet.Cells[5, 2] = orangetotal;
OfficeSheet.Cells[6, 2] = grapestotal;
OfficeExcel.Visible = true;
OfficeWorkBook.SaveAs("D:\\fruits\\" + MonthYear + ".xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel7, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
break;
case "2":
OfficeWorkBook = OfficeExcel.Workbooks.Open("D:\\fruits\\" + MonthYear + ".xls");
OfficeSheet = (Excel.Worksheet)OfficeWorkBook.Worksheets.get_Item(1);
OfficeSheet.Cells[2, 3] = dtpDay + dtpMonth;
OfficeSheet.Cells[3, 3] = appletotal;
OfficeSheet.Cells[4, 3] = bananatotal;
OfficeSheet.Cells[5, 3] = orangetotal;
OfficeSheet.Cells[6, 3] = grapestotal;
OfficeExcel.Visible = true;
OfficeWorkBook.Save();
break;
.
.
.
so On.....
}
Thank you
Upvotes: 2
Views: 87
Reputation: 136
int DayCell = dateTimePicker1.Value.Day+1;
OfficeSheet.Cells[2, Daycell] = dtpDay + dtpMonth ;
Put the day value to a variable and use it as an indexer.
Upvotes: 1