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.
Related
Nowadays am working on a c# desktop application and in this application after a transaction completed that transaction export in excel but I want to make an excel font size bold I don't know how to do it please help me in this scenario.
Thanks.
here is my code
//creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
//creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
//creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
//see the excel sheet behind the program
app.Visible = true;
//get the reference of first sheet. By default its name is Sheet1.
//store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
//changing the name of active sheet
worksheet.Name = "Exported from gridview";
//storing header part in Excel
//
worksheet.Cells[1, 1] = "Customer Name";
worksheet.Cells[1, 2] = "S/D/W";
worksheet.Cells[1, 3] = "NIC";
worksheet.Cells[1, 4] = "Postal Address";
worksheet.Cells[1, 5] = "Flat No";
worksheet.Cells[1, 6] = "Type";
worksheet.Cells[3, 1] = "Floor";
worksheet.Cells[3, 2] = "Block";
worksheet.Cells[3, 3] = "Size";
worksheet.Cells[3, 5] = "File No";
worksheet.Cells[3, 6] = "Nominee";
worksheet.Cells[5, 1] = "Relation";
worksheet.Cells[5, 2] = "nominee_NIC";
worksheet.Cells[5, 3] = "Contact_NIC";
worksheet.Cells[5, 4] = "Status";
worksheet.Cells[5, 5] = "Booking Station";
worksheet.Cells[5, 6] = "Booked By";
worksheet.Cells[7, 1] = "Cost";
worksheet.Cells[7, 2] = "Discount";
worksheet.Cells[7, 3] = "Total";
workbook.SaveAs("D:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
worksheet.Cells[1, 1].Font.Bold = true; should do the job
I am having a problem with my app when trying to run on the server.
In my place it works fine but when passed to the server it fails to try to create the pivotcache.
Excel has permissions on the server with the user IIS, on my computer I have Office 365 and Office 2010 on server.
please help.error
Excel.Application oApp;
Excel.Worksheet oSheet;
Excel.Workbook oBook;
//Create COM Objects. Create a COM object for everything that is referenced
oApp = new Excel.Application();
oBook = oApp.Workbooks.Open(fileTest);
oSheet = oBook.Sheets[1];
//Range = oSheet.Range["A9","BN36"];
//Excel.Worksheet oSheet2 = oBook.Worksheets.Add();
//oSheet2.Name = "Pivot Table";
//oApp = new Excel.Application();
//oBook = oApp.Workbooks.Add();
//oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
//oSheet.Cells[1, 1] = "Name";
//oSheet.Cells[1, 2] = "Salary";
//oSheet.Cells[2, 1] = "Frank";
//oSheet.Cells[2, 2] = 150000;
//oSheet.Cells[3, 1] = "Ann";
//oSheet.Cells[3, 2] = 300000;
Excel.Range last = oSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = oSheet.get_Range("A1", last);
int lastUsedRow = last.Row;
int lastUsedColumn = last.Column;
//// now capture range of the first sheet = I will need this to create pivot table
Excel.Range oRange = oSheet.Range["A1", "AJ708"];
// create second sheet
if (oApp.Application.Sheets.Count < 2)
{
oSheet = (Excel.Worksheet)oBook.Worksheets.Add();
}
else
{
oSheet = oApp.Worksheets[2];
}
oSheet.Name = "Resumen";
// specify first cell for pivot table
Excel.Range oRange2 = oSheet.Cells[1, 1];
// create Pivot Cache and Pivot Table heres trow exception error
Excel.PivotCache oPivotCache = (Excel.PivotCache)oBook.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, oRange);
Excel.PivotTable oPivotTable = (Excel.PivotTable)oSheet.PivotTables().Add(PivotCache: oPivotCache, TableDestination: oRange2, TableName: "Summary");
solved.
trying change this line
var oPivotCache = pivotCaches.Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!$A$1:$AL$" + lastUsedRow);
the correct format to pass a range on office 2010 i think so.
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'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.
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();