你好,任何人都可以帮我解决这个问题,我这里有一个代码可以计算从 B 列到 AF 列的水果数量(31 天) 我使用了从案例 1 到案例 31 的开关。我希望我的代码简单或循环。 31 案例太长了。顺便说一下我的代码的工作方式,我只是希望它简短。
这是我的代码
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.....
}
谢谢
最佳答案
int DayCell = dateTimePicker1.Value.Day+1;
OfficeSheet.Cells[2, Daycell] = dtpDay + dtpMonth ;
将日期值放入变量并将其用作索引器。
关于c# - 将值从标签放入 excel 列的简短或简单的解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357027/