在excel中将值从标签放到列的简短或简单的解决方案
本文关键字:解决方案 简单 excel 标签 | 更新日期: 2023-09-27 18:27:28
大家好,任何人都可以帮我解决这个问题,我这里有一个代码,可以计算从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 ;
将day值放入变量中,并将其用作索引器。