I know that this problem may be addressed in another asked question, is not cause I lost 2 days trying them all. Lets start the topic: -I have an desktop app made in Visual Studio Express 2017, C# code used. -I take 3 variables that I want to store in an excel document that has multiple sheets: Overtime nr. of hours, Day, comment. Every sheet belongs to an individual that is based on pc username.
string datforOV = monthCalendar1.SelectionRange.Start.ToShortDateString(); //data string
double hours = decimal.ToDouble(numericUpDown1.Value) + decimal.ToDouble(numericUpDown2.Value) * 0.1; //number of hours
string box = richTextBox1.Text; //content of text box
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet xlsht = new Microsoft.Office.Interop.Excel.Worksheet();
string path = @"Z\OLP.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets[Environment.UserName];
I need to add a new row, in the sheet named already after the Username, and fill the first column with nr of hours, second column with the day, and the next one with the comment. Please help me cause I started losing my minds. Thank in advance.
You can try the following code to add a new row to your named sheet excel.
using Excel = Microsoft.Office.Interop.Excel;
private void button1_Click(object sender, EventArgs e)
{
string datforOV = monthCalendar1.SelectionRange.Start.ToShortDateString(); //data string
double hours = decimal.ToDouble(numericUpDown1.Value) + decimal.ToDouble(numericUpDown2.Value) * 0.1; //number of hours
string box = richTextBox1.Text; //content of text box
Excel.Application xlApp = new Excel.Application();
string path = @"E:\1.xlsx";
Excel.Workbook workbook = xlApp.Application.Workbooks.Open(path);
Excel.Worksheet xlsht =workbook.Worksheets[Environment.UserName];
Excel.Range range = xlsht.UsedRange;
int rowcount = range.Rows.Count;
Excel.Range next= (Excel.Range)xlsht.Rows[rowcount+1];
next.Insert(); //Another method to add new row
xlsht.Cells[rowcount + 1, 1] = datforOV;
xlsht.Cells[rowcount + 1, 2] = hours;
xlsht.Cells[rowcount + 1, 3] = box;
workbook.Save();
workbook.Close();
xlApp.Quit();
MessageBox.Show("sucess");
}
Result:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.