I am creating a simple application in C# where I am saving the data in an already created Excel sheet. To do this, first I am reading the data from the rows and if that row is empty that means I have to save my new data in it. I have an excel sheet with following details:
S.No | Name | Email ID | Phone Number
So I first check which is the last S.No. Let's say if it is 4, this means I have to enter data in 6th row with S.No = 5 because one row is taken by the header.
To do this I am first opening the excel file and then scanning the rows. I am able to scan it but when I try to save it, it replace the current file with new one and old data is lost. Here is what I am doing:
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("<filepath>", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for(parse = 2; parse <= 100; parse++)
{
if (xlRange.Cells[parse, 1].Value2 != null)
{
Sno++;
}
else
{
break;
}
}
//Sno contains the recent serial number
After this I am just filling the data and saving the file:
xlWorksheet.Cells[Sno + 2, 1] = Sno + 1;
xlWorksheet.Cells[Sno + 2, 2] = NameTextBox.Text;
xlWorksheet.Cells[Sno + 2, 3] = EmailIdTextBox.Text;
xlWorksheet.Cells[Sno + 2, 4] = PhoneNumberTextBox.Text;
xlWorksheet.SaveAs("<filepath>");
xlWorkbook.Close();
xlApp.Quit();
But at the time of saving it says file already exit because I am doing SaveAs. Is there any way to just save the file or any other alternative.
Please help.
For saving see this
Also consider the workaruond I said in comment.
Related
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:
I have a list of numbers in one class. I am trying to export the data in the list and the data in array[4,4] to Excel. I would like the list as one column with the header and the array as a table with headers (column name) and row names.
I did not find a proper solution to try
public void Data_to_Excel()
{
//start excel
NsExcel.Application excapp = new Microsoft.Office.Interop.Excel.Application();
//if you want to make excel visible
excapp.Visible = true;
//create a blank workbook
var workbook = excapp.Workbooks.Add(NsExcel.XlWBATemplate.xlWBATWorksheet);
//or open one - this is no pleasant, but yue're probably interested in the first parameter
string workbookPath = " filepath here ";
workbook = excapp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Not done yet. You have to work on a specific sheet - note the cast
//You may not have any sheets at all. Then you have to add one with NsExcel.Worksheet.Add()
var sheet = (NsExcel.Worksheet)workbook.Sheets[1]; //indexing starts from 1
//do something usefull: you select now an individual cell
//var range = sheet.get_Range("A1", "A1");
//range.Value2 = "test"; //Value2 is not a typo
//now the list
string cellName;
int counter = 1;
foreach (var item in Sim_Obj.Bottom_Rows_Count_Stack)
{
cellName = "A" + counter.ToString();
var range = sheet.get_Range(cellName, cellName);
range.Value2 = item.ToString();
++counter;
}
workbook.SaveAs("Cash_Surge_Sim_Results.xlsx");
}
I have the 20 results in the rich text box in a list.
I have table layout data in an array[4,4]
I want the array data as a table form in Excel and
the list data as one column.
I have problem with C# Interop Excel get valid range with big file
https://www.dropbox.com/s/betci638b1faw8g/Demo%20Training%20Data.xlsx?dl=0
This is my file but real size is 1000 but I got 49998
I used standard code
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(txtbTrainPath.Text);
Excel.Worksheet xlWorksheet = xlWorkbook.Worksheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlApp.Visible = true;
xlWorksheet.Columns[5].Delete();
xlWorksheet.Columns[3].Delete();
rowCount = xlRange.Rows.Count;
colCount = xlRange.Columns.Count;
Only for this file is not work correctly, other files works well. Please help me to find what is the problem. How to resize worksheet for only valid size.
I would use this approach to get the Rows and Columns count which will return the result of the cells which are not empty.
// Find the last real row
lastUsedRow = worksheet.Cells.Find("*",System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;
// Find the last real column
lastUsedColumn = worksheet.Cells.Find("*", System.Reflection.Missing.Value,
System.Reflection.Missing.Value,System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Column;
Here is the complete code for your reference:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = null;
Excel.Workbook wb = null;
Excel.Worksheet worksheet = null;
int lastUsedRow = 0;
int lastUsedColumn = 0;
string srcFile = #"Path to your XLSX file";
xlApp = new Excel.ApplicationClass();
xlApp.Visible = false;
wb = xlApp.Workbooks.Open(srcFile,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
worksheet = (Excel.Worksheet)wb.Worksheets[1];
Excel.Range range
// Find the last real row
lastUsedRow = worksheet.Cells.Find("*",System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;
// Find the last real column
lastUsedColumn = worksheet.Cells.Find("*", System.Reflection.Missing.Value,
System.Reflection.Missing.Value,System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Column;
xlApp.Workbooks.Close();
xlApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xlApp);
After downloading the excel file and taking a look at it, I found as I expected, formatting on row 49998 column C. The font was different, the number formatting was different and the font color was red. I simply deleted all the cells on row 49998 and this simply decreased the number of used range rows to 49997. You could play this guess which cells have formatting by deleting the last row then check again. I have a feeling ALL cells above row 49998 have some kind of different formatting.
To fix this one sheet to get the proper used range. You have two choices. 1) Select the WHOLE row starting at row 1001, then scroll down to row 49998. With the SHIFT key pressed, click on the WHOLE row 49998. With rows 1001 to 49998 selected, right click on the selection and select "Delete" and possibly, if it asks, shift the cells up. Or 2) copy the cells with data only and paste the cells into an new worksheet, delete the old worksheet and rename the new worksheet to the previous worksheet name. I hope this makes sense.
My aim is to check line per line in the Sheet1 in order to discover how many rows are, so i put a do\while that should stop once it reaches a blank cell
Example:
row1 data row2 data row3 datarow4 datarow5 data
row6 data row7 data
In this case I need only the first 5 rows, so the do\while check is intended to stop once it reaches the blank cell. This doesn't happens, because the check doesn't loop (it stops after completing a circle like it finds a blank cell even if it is filled with data).
string str;
int rCnt = 11; //the data I need is after the 10th row in excel
int cCnt = 1;
int valori = 1;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(label4.Text, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows,
"", true, false, 0, true, false,
false);
Excel.Sheets xlsheet = xlWorkbook.Worksheets;
string sheet1 = "Sheet1";
Excel.Worksheet xlWorksheet = (Excel.Worksheet)xlsheet.get_Item(sheet1);
Excel.Range xlCell;
do
{
rCnt++;
str = "A" + rCnt;
xlCell = (Excel.Range)xlWorksheet.get_Range(str, str);
} while (xlCell.Value2 == null);
I tried changing Value2 to Value or Text and trying to set == "" instead of null.
If you want the loop stop when reach blank cell then .. Try to change
while (xlCell.Value2 == null);
with
while (! IsNull(xlCell.Value2));
Simple way to check a cell is empty:
if (sheet.Cells[4,3] == null || sheet.Cells[4,3].Value2 == null || sheet.Cells[4,3].Value2.ToString() == "")
MessageBox.Show(“cell on row 4 col 3 is empty”);
You can use the Text property of the selected cell. It can be converted to a string type via "as". The result string can already be checked as usual in C#, like not-empty
string TempText = excelWorksheet.Cells[1, 1].Text as string;
if (!string.IsNullOrWhiteSpace(TempText)){
// actions
}
The issue mainly comes from when you don't know what sort of data to expect. When I work with Excel reads I often do something similar to:
var _cell = range.Cells[1, 2].Value2;
if (_cell.GetType() != typeof(Double))
In your instance if you always are getting a string returned then you should be able to assume the cast:
string _str = (string)(range.Cells[str, str] as Excel.Range).Value2;
and then check that is not empty.
This is working for me:
using Excel = Microsoft.Office.Interop.Excel; to read excelsheet:
var excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorkbook.Sheets[2];
Excel.Range excelRange = excelWorksheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
string wwdEmpty = Convert.ToString(excelRange.Cells[5, 14].value2);
// this is working code with NULL Excell cell
do
{
rCnt++;
str = Sheet.Cells[rCnt, 5].Value;
} while (str != null);
Im reading an Excel document from C# Windows Form.. There are 25 worksheets in Excel Workbook.. i can read 1st worksheet successfully.. But when i change it to worksheet 2.. it won't working at all.. Im not using OLEDB..
I want to read 100 Row in every sheet.. following is my code...
` dt.Columns.Add("Amount", typeof(double));
dt.Columns.Add("ChequeNo", typeof(int));
dt.Columns.Add("month", typeof(int));
int AmountRow = 100;
int ChequeNoRow = 101;
int Column = 3;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[2];\\This place is the changing worksheets
range = xlWorkSheet.UsedRange;
double chequeAmount;
double chequeNo;
for (int i = Column; i < 15; i++)
{
chequeAmount = (double)(range.Cells[AmountRow, i] as Excel.Range).Value2;
chequeNo = (double)(range.Cells[ChequeNoRow, i] as Excel.Range).Value2;
if (chequeNo != 0.0)
{
dt.Rows.Add(Convert.ToDouble(chequeAmount), Convert.ToInt32(chequeNo), i);
}
}
dataGridView1.DataSource = dt;
xlWorkBook.Close(true, null, null);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);`
releaseObject methods are not here.. those working perfectly...
`xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];`
This is how i change my worksheets.. The following line gives an exception..[Null point Exception]
chequeAmount = (double)(range.Cells[AmountRow, i] as Excel.Range).Value2;
Hope you'll know answers..
Try this instead:
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[2];
The Sheets property can include non-worksheet sheets, which could be the issue in your scenario.