I am working with a windows form application using c#. This program is able to read the data from the sql server and then and export to excel. I got this part working. However, I want to be able to generate a list of random password in a column according to how many rows of item I have in my excel. Let say my password column is column 'M' (password) and let say if the excel file has ten items (10 rows), then column 'M' will display 10 random generated password. If there is 5 item, then column 'M' will display 5 random password. I am thinking to use for loop to do this. But I have not idea where to start. Help will be appreciated. I am using Microsoft.interop.excel library 15.
Here is the password pattern that I want
abcd001
abcd002
abcd003
abcd004
abcd005
In the excel let say if I have 10 rows, then 10 column M it will display a list of password
A B C ..... M
1 abcd001
2 abcd002
3 abcd003
4 abcd004
5 abcd005
6 abcd006
7 abcd007
8 abcd008
9 abcd009
10 abcd010
Here is the part of my code to create excel file
private void exportToExcel(){
object missing = Type.Missing;
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = false;
Excel.Workbook xlwb = xlApp.Workbooks.Add(missing);
Excel.Worksheet xlEmployeeDetail= xlwb.ActiveSheet as Excel.Worksheet;
xlEmployeeDetail.Name = "Employee Detail";
xlEmployeeDetail.Cells[1, 1] = "Employee Id";
xlEmployeeDetail.Cells[1, 2] = "First Name";
xlEmployeeDetail.Cells[1, 3] = "Last Name";
xlEmployeeDetail.Cells[1, 4] = "Nick Name";
xlEmployeeDetail.Cells[1, 5] = "Email";
xlEmployeeDetail.Cells[1, 6] = "Entry Year";
xlEmployeeDetail.Cells[1, 7] = "Leave Year";
.........
xlEmployeeDetail.Cells[1, 12] = "User Login ID";
xlEmployeeDetail.Cells[1, 13] = "Password";
while (dr.Read())
{
i++;
int e_id = dr.GetInt32(1);
string f_Name = dr.GetString(5);
string l_Name = dr.GetString(6);
string n_Name = dr.GetString(7);
string e_email = dr.GetString(8);
int e_Year = dr.GetInt32(9);
//int l_Year = dr.GetInt32(10);
xlEmployeeDetail.Cells[i, 1] = t_id;
xlEmployeeDetail.Cells[i, 2] = f_Name;
xlEmployeeDetail.Cells[i, 3] = l_Name;
xlEmployeeDetail.Cells[i, 4] = zh_Name;
xlEmployeeDetail.Cells[i, 5] = t_email;
xlEmployeeDetail.Cells[i, 6] = e_Year;
.....
}
dr.Close();
}
Firstly, create a mutual prefix for your password before the while loop.
string passwordPrefix = "abcd";
Then, inside the loop, add the prefix to a properly formatted i.ToString() (using String.Format). You might want to create the format dynamically, because you might need 000 or 0000 etc., depending on the number of rows.
Related
I am using this code to create an excel instance which is used for making a report
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = true;
excel.DisplayAlerts = false;
worKbooK = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worKsheeT = worKbooK.Worksheets[1]; ;
worKsheeT.Name = "Report";
iCountW = 2;
worKsheeT.Cells[1, 1] = "S.No";
worKsheeT.Cells[1, 2] = "Weld Stud/Nut Name";
worKsheeT.Cells[1, 3] = "Weld Spot Clearance Status";
worKsheeT.Cells[1, 4] = "Weld Spot Name";
worKsheeT.Cells[1, 5] = "Coord-X";
worKsheeT.Cells[1, 6] = "Coord-Y";
worKsheeT.Cells[1, 7] = "Coord-Z";
// Some Code
// Some more code
// No more code
After updating the data rows of this report I am using the below code for saving the excel workbook which is not letting me save the workbook.
string filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory) + "\\" + "Trial_StudNut.xlsx";
if (!System.IO.File.Exists(filename))
{
worKbooK.SaveAs(filename, Excel.XlSaveAsAccessMode.xlNoChange);
}
Can someone help me with what am I missing to avoid exceptions while saving the workbook?
Edit: I am getting the following
(HRESULT: 0x800A03EC Error while saving Excel file)
The code is getting inside the condition and then falling into the exception.
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'm trying to copy data from textboxes and set them on specific cells on Excel file In which have 2 sheets and sheet 1 named as "PM" and sheet 2 named as "4-10-2018" the process successfully done but on the second sheet not display data properly.
I checked my code many times but found nothing to fix this issue.
Code:
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 = #"D:\test.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["PM"];
xlsht.Cells[11, 2] = UserNameTxt.Text + "#rasatop.com";
xlsht.Cells[11, 4] = UserNameTxt.Text;
xlsht.Cells[14, 2] = SerialTxt.Text;
xlsht.Cells[16, 2] = WLANMacTxt.Text;
xlsht.Cells[16, 3] = LANMacTxt.Text;
xlsht.Cells[16, 4] = IPTxt.Text;
xlsht.Cells[14, 5] = ComputerTxt.Text;
xlsht.Cells[16, 5] = BarcodeTxt.Text;
xlsht.Cells[18, 5] = CPUTxt.Text.Substring(0, 26);
xlsht.Cells[18, 4] = VGATxt.Text;
xlsht.Cells[18, 3] = RAMTxt.Text;
xlsht.Cells[27, 4] = OSTxt.Text;
xlsht.Cells[5, 4] = System.DateTime.Today;
xlsht.Cells[26, 4] = System.DateTime.Today;
xlsht.Cells[9, 5] = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
xlApp.Visible = true;
Microsoft.Office.Interop.Excel.Worksheet xlsht2 = new Microsoft.Office.Interop.Excel.Worksheet();
xlsht2 = xlApp.Application.Workbooks.Open(path).Worksheets["4-10-2018"];
xlsht2.Cells[4, 2] = System.DateTime.Today;
xlsht2.Cells[6, 2] = UserNameTxt.ToString();
xlsht2.Cells[6, 4] = ComputerTxt.ToString();
xlsht2.Cells[6, 5] = BarcodeTxt;
And after executing the code run successfully but data displayed as below in Screenshot:
Display Error:
In some places you are putting calling the .ToString() method of the TextBox control into your spreadsheet cell rather than reading its UserNameTxt.Text property which will contain the value.
Here is your problem UserNameTxt.ToString(). You have to getText property for TextBox value. Convert UserNameTxt.ToString()to UserNameTxt.Text
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.
I'm trying to create a excel from a datagrid with wpf, however when I format a column to just text it still converts some columns to what I presume to be a date conversion.
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
This is how the conversion of the column is set, but this results in Excel still formatting some fields to a date-ish value... If you look at the column foutcode you'll see what I mean.
results in:
I think what happens is that it automatically recognizes the value and sees if it fits a date format while I'm telling it to handle as just regular text! So does anyone have any idea on how to get rid of that? because the data is unusable because of this small error. Maybe use a more specific format than just text? however I can't seem to figure out how.
Also Convert a lot of rows into excel takes some quite a bit of time (4-5s for 1000 rows). Is there a way to make it go faster? All help is really appreciated.
public void ExportToExcel(List<Fouten> data)
{
try
{
if (data.Count > 0)
{
// Displays a SaveFileDialog so the user can save the Image
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Excel File|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.FileName = "Data rapport";
// If the User Clicks the Save Button then the Module gets executed otherwise it skips the scope
if ((bool)saveFileDialog1.ShowDialog())
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp != null)
{
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int rowCount = 1;
xlWorkSheet.Cells[rowCount, 1] = "Datum";
xlWorkSheet.Cells[rowCount, 2] = "Tijd";
xlWorkSheet.Cells[rowCount, 3] = "Foutcode";
xlWorkSheet.Cells[rowCount, 4] = "Omschrijving";
xlWorkSheet.Cells[rowCount, 5] = "Module";
xlWorkSheet.Cells[rowCount, 6] = "TreinId";
rowCount++;
Excel.Range rg = (Excel.Range)xlWorkSheet.Cells[1, 2];
rg.EntireColumn.NumberFormat = "hh:mm:ss.000";
Excel.Range rg1 = (Excel.Range)xlWorkSheet.Cells[1, 3];
rg1.EntireColumn.NumberFormat = "text";
foreach (Fouten item in data)
{
string[] moduleNaam = item.Module.Split('_');
xlWorkSheet.Cells[rowCount, 1] = item.Datum;
xlWorkSheet.Cells[rowCount, 2] = item.Time.ToString();
xlWorkSheet.Cells[rowCount, 3] = item.FoutCode;
xlWorkSheet.Cells[rowCount, 4] = item.Omschrijving;
xlWorkSheet.Cells[rowCount, 5] = moduleNaam[0].ToUpper();
xlWorkSheet.Cells[rowCount, 6] = item.TreinId;
rowCount++;
}
xlWorkSheet.Columns.AutoFit();
// If the file name is not an empty string open it for saving.
if (!String.IsNullOrEmpty(saveFileDialog1.FileName.ToString()) && !string.IsNullOrWhiteSpace(saveFileDialog1.FileName.ToString()))
{
xlWorkBook.SaveAs(saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel File Exported Successfully", "Export Engine");
}
}
}
}
else
{
MessageBox.Show("Nothing to Export", "Export Engine");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The Range.NumberFormat property for Text is an 'at' symbol (e.g. capital 2 or #), not the word Text.
rg1.EntireColumn.NumberFormat = "#";
More at Number Format Codes.