Excel Sheet Not Saving Data in Sheet 1 - c#

I Excel File with 2 sheets, First sheet named as "PM" and second Sheet named as "km" when i try to enter data to sheet 1 from textboxes it successfully done but when i tried to enter data in sheet 2.. sheet 1 back to its original state(Empty)..
I checked the code i made at first 1 worksheet "xlsht" for both sheets but data not updated on both sheets then i made 2 functions with 2 worksheets but the problem is same, any idea why?
My Code:
protected void PM_Sheet1()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new 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;
xlsht.SaveAs(#"D:\test1.xlsx");
}
catch (Exception)
{
MessageBox.Show(#"Make Sure test.xlsx file in D:\ Drive");
}
}
protected void PM_Sheet2()
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Worksheet xlsht = new Worksheet();
string path = #"D:\test1.xlsx";
xlsht = xlApp.Application.Workbooks.Open(path).Worksheets["km"];
xlsht.Cells[4, 2] = System.DateTime.Today;
xlsht.Cells[6, 2] = UserNameTxt.Text;
xlsht.Cells[6, 4] = ComputerTxt.Text;
xlsht.Cells[6, 5] = BarcodeTxt.Text;
xlsht.SaveAs(#"D:\" + ComputerTxt.Text + ".xlsx");
xlApp.Visible = true;
}
catch (Exception)
{
MessageBox.Show("Error Occured Cannot Save Sheet 2");
}
}

despite documentation, Worksheet.SaveAs() would lead to an error, so you have to use Workbook.SaveAs()
You're also opening two different Excel instances where you need only one and apparently leaving both them running!
Finally, you'd better open an Excel instance for all operations and hence distributing necessary code at Form class level (declarations), button1_Click() level (Excel and Workbook initialization), helper methods (Worksheet initializations)
As follows:
using System;
using System.Windows.Forms;
using Worksheet = Microsoft.Office.Interop.Excel.Worksheet;
using Workbook = Microsoft.Office.Interop.Excel.Workbook;
using MsExcelApp = Microsoft.Office.Interop.Excel.Application;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
MsExcelApp xlApp =;
Workbook xlWb;
Worksheet xlSht;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"D:\test.xlsx";
xlApp = new MsExcelApp();
try
{
xlWb = xlApp.Application.Workbooks.Open(path);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
PM_Sheet1();
PM_Sheet2();
try
{
xlWb.SaveAs(#"D:\" + ComputerTxt.Text + ".xlsx");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
xlApp.Quit();
}
protected void PM_Sheet1()
{
try
{
xlSht = xlWb.Worksheets["PM"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
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;
}
protected void PM_Sheet2()
{
try
{
xlSht = xlWb.Worksheets["km"];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
xlSht.Cells[4, 2] = System.DateTime.Today;
xlSht.Cells[6, 2] = UserNameTxt.Text;
xlSht.Cells[6, 4] = ComputerTxt.Text;
xlSht.Cells[6, 5] = BarcodeTxt.Text;
}
}
}

Related

Exporting SQL table to Excel in C# is randomly picking cells formats for dates

I am trying to export an SQL Dataset to an excel document.
At certain points when outputting the date fields the excel cells are being formatted at certain points as date cells and some as general.
This is causing the dates to display sometime in the format that I want, UK style day/month/year, in the American style month/day/year.
If it was just one way that would be fine because the report would be at least consistent. However the fact that the code will sometime output the correct format and sometimes won't is very annoying
My code so far:
private void doReport(DataSet myDS)
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
int i;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Report produced on the " + System.DateTime.Now.ToString("dd/MM/yyyy");
xlWorkSheet.Cells[3, 1] = "Project Type";
xlWorkSheet.Cells[3, 2] = "Client";
xlWorkSheet.Cells[3, 3] = "Date Started";
xlWorkSheet.Cells[3, 4] = "Target Date";
xlWorkSheet.Cells[3, 5] = "Date Completed";
xlWorkSheet.Cells[3, 6] = "Stage Target";
xlWorkSheet.Cells[3, 7] = "Stage";
xlWorkSheet.Cells[3, 8] = "Assigned To";
xlWorkSheet.Cells[3, 9] = "Notes";
i = 4;
foreach (DataRow row in myDS.Tables[0].Rows)
{
xlWorkSheet.Cells[i, 1] = row["strProjectDescription"];
xlWorkSheet.Cells[i, 2] = row["strClient"];
DateTime dteProjStart = (DateTime)row["dteProjectStart"];
xlWorkSheet.Cells[i, 3] = dteProjStart.ToString("dd/MM/yyyy");
DateTime dteProjTarget = (DateTime)row["dteProjectTarget"];
xlWorkSheet.Cells[i, 4] = dteProjTarget.ToString("dd/MM/yyyy");
if (rbViewProjectsCompletedVal.Checked)
{
DateTime dteProjFin = (DateTime)row["dteProjectFinished"];
xlWorkSheet.Cells[i, 5] = dteProjFin.ToString("dd/MM/yyyy");
}
if (row.IsNull("dteProjectStageTarget") == false)
{
DateTime dteProjStageTar = (DateTime)row["dteProjectStageTarget"];
xlWorkSheet.Cells[i, 6] = dteProjStageTar.ToString("dd/MM/yyyy");
}
xlWorkSheet.Cells[i, 7] = row["strProjectStageDescription"];
xlWorkSheet.Cells[i, 8] = row["initials"];
xlWorkSheet.Cells[i, 9] = csSQL.runSQL("select strProjectNotes from tbl_AdminSupport_Projects where intASProjectID = " + row["intASProjectID"], "Management").Tables[0].Rows[0]["strProjectNotes"];
i++;
}
xlWorkSheet.Columns.AutoFit();
xlWorkSheet.Rows.AutoFit();
xlApp.Visible = true;
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Dataset structure:
Any item prefixed with str is a nvarchar(max), dte is a date

Data copied from Textboxes to be displayed on Excel cell not display

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

Excel numberformatting

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.

Create excel file and download it without saving it into the server, is it possible?

i have managed to create an excel file with interop, and now i want that excel file to be downloaded
in web browser instead of saving in in drive.
var xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet xlWorkSheet = xlWorkBook.Sheets[1];
Excel.Range chartRange;
var attendance_list = CTX.schedules.Where(s => s.event_id == Convert.ToInt32(param));
if (attendance_list.Count() > 0)
{
xlWorkSheet.Cells[1, 1] = "PIC : ";
xlWorkSheet.Cells[2, 1] = "Tempat : ";
xlWorkSheet.Cells[1, 2] = attendance_list.FirstOrDefault().calendar_event.PIC;
xlWorkSheet.Cells[2, 2] = attendance_list.FirstOrDefault().calendar_event.sched_loc;
xlWorkSheet.Shapes.AddPicture(#Server.MapPath("~/Images/" + "oto_group2.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 50, 50, 100, 45);
xlWorkSheet.Shapes.AddPicture(#Server.MapPath("~/Images/" + "oto_group3.png"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 280, 50, 100, 45);
int row = 10;
int idx = 0;
xlWorkSheet.Cells[9, 1] = "No";
xlWorkSheet.Cells[9, 2] = "Name";
xlWorkSheet.Cells[9, 3] = "Phone";
xlWorkSheet.Cells[9, 4] = "Time";
xlWorkSheet.Cells[9, 5] = "Branch";
xlWorkSheet.Cells[9, 6] = "Sign";
xlWorkSheet.Cells[9, 7] = "Note";
chartRange = (xlWorkSheet.get_Range("b9"));
chartRange.ColumnWidth = 40;
chartRange = (xlWorkSheet.get_Range("c9"));
chartRange.ColumnWidth = 20;
chartRange = (xlWorkSheet.get_Range("g9"));
chartRange.ColumnWidth = 20;
var key = CTX.translate_value_ms.Where(t => t.PSF_type == "HRS_PHONE_TYPE"
&& t.value == "CELL").FirstOrDefault().translate_value_id;
foreach (var item in attendance_list)
{
idx++;
var hp = item.user_list.user_phones.Where(p => p.phone_type_id == key).FirstOrDefault();
xlWorkSheet.Cells[row, 1] = idx;
xlWorkSheet.Cells[row, 2] = displayFullName(item.user_list.fname, item.user_list.mname, item.user_list.lname);
xlWorkSheet.Cells[row, 3] = hp.phone_number;
xlWorkSheet.Cells[row, 4] = item.calendar_event.time_range;
xlWorkSheet.Cells[row, 5] = item.calendar_event.branch;
xlWorkSheet.Cells[row, 6] = "";
xlWorkSheet.Cells[row, 7] = "";
row++;
}
chartRange = xlWorkSheet.get_Range("a9", "g9");
chartRange.Font.Bold = true;
chartRange.Interior.Color = System.Drawing.Color.Gray;
chartRange = xlWorkSheet.get_Range("a9", "g" + (row - 1));
chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal);
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
this is what i have tried so far to create excel file. need some englightment. "this code save excel file to drive, which is not the result that i want to achieve."
this is my generated excel :
You will need to save the file on the server temporarily in order to serve it to the client.
You can save it in a temp path using utilities in System.IO.Path like GetTempPath() to put the file in a place the OS will clean the file up automatically when it's not needed.
I don't know what web server you're using but if you're using MVC you'd do something like this to serve the file in your controller
var filePath = System.IO.Path.GetTempFileName();
//then save the file to the filePath
return File(filePath);
I used https://npoi.codeplex.com/ to create excel and returned a FileStereamResult on my controller action.
I think you cannot do that with the Excel library you are using
How to write an Excel workbook to a MemoryStream in .NET?
But check out npoi is really simple and they even have an example on what you are looking, which was something like this
public FileStreamResult MyAction(parameters)
{
var workBook = CreateWorkbook(parameters);
var stream = new MemoryStream();
workBook.Write(stream);
stream.Position = 0;
return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
}
Like this you dont save anything to the file system.
Using a mix of your work and the example I made using NPOI you can do something like this
public FileStreamResult MyAction(parameters)
{
//Here you create a workBook with your actual code
var workBook = CreateWorkbook(parameters);
var fileName = "routeToFileWhereYourAppCanWrite.xls"
//Here you save the file to the file system
workbook.SaveToFile(fileName);
using (MemoryStream ms = new MemoryStream())
{
using (FileStream fileStream = new FileStream("file.bin", FileMode.Open, FileAccess.Read))
{
fileStream.CopyTo(ms);
}
//Here you delete the saved file
File.Delete(fileName);
ms.Position = 0;
return File(stream, "attachment;filename=myfile.xls", "myfile.xls");
}
}
In summary, create the file as you do now, save it, load it into memory, delete it and return the stream
Paste this snippet code own project under Marshal.ReleaseComObject(xlApp); this line.
After that set path where your file save in system.
I hope this code will work.
string fileName = "";
Response.ContentType = "application/vnd.ms-excel";
fileName = Server.MapPath("~/WriteReadData/Excelfiles/Excelfile.xls");
//Give path name\file name.
Response.AppendHeader("Content-Disposition", "attachment; filename="Excelfile.xls");
//Specify the file name which needs to be displayed while prompting
Response.TransmitFile(fileName);
Response.End();

Add text to row 1 in excel export listview

I want to name each column in the first row of the excel sheet, I get an exception on the first line of naming the columns. Please advise?
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = xla.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xla.ActiveSheet;
int i = 2;
int j = 1;
if (comboBox1.Text == "Brickcom")
{
try
{
ws.Rows[j, 1] = "Category";
ws.Rows[j, 2] = "Part Number";
ws.Rows[j, 3] = "TradePrice";
ws.Rows[j, 4] = "Product";
ws.Rows[j, 5] = "Resolution";
ws.Rows[j, 6] = "Included Accessories";
ws.Rows[j, 7] = "Major Acc Price";
foreach (ListViewItem comp in listView1.Items)
{
ws.Cells[i, j] = comp.Text.ToString();
foreach (ListViewItem.ListViewSubItem drv in comp.SubItems)
{
ws.Cells[i, j] = drv.Text.ToString();
j++;
}
j = 1;
i++;
}
xla.Visible = true;
}
catch
{
MessageBox.Show("Export did not work");
}
}
Try this:
ws.Cells[j, 1] = "Category";
ws.Cells[j, 2] = "Part Number";
ws.Cells[j, 3] = "TradePrice";
...
i would use stream writer :
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "CSV|*.csv";
savefile.RestoreDirectory = true;
savefile.ShowDialog();
string filename = savefile.FileName;
if (filename != "")
{
StreamWriter ofile = new StreamWriter(filename);
ofile.WriteLine("Category, Part Number, TradePrice, ..."); //just separate using a comma ,
//your complete writings here
ofile.Close(); //close the streamwriter and you're done
}
good luck

Categories