Can't open the excel file after generating it on server side - c#

I have generated the excel file using C# coding as shown below
C# Coding:
protected void Page_Load(object sender, EventArgs e)
{
var doc = new SpreadsheetDocument(#"D:\JOSEPH\GenerateExcelSheet\OpenXmlPackaging.xlsx");
Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
sheet1.Cells[1, 1].Value = "Test";
sheet1.Cells["A1"].Value = 1;
sheet1.Cells["C3"].Style = new OpenXmlPackaging.Style {
Borders = new Borders(BorderStyles.Thick),
Font = new Font
{
Name = "Consolas",
Size = 10,
Style = FontStyles.DoubleUnderline | FontStyles.Bold
},
NumberFormat = new NumberFormat("#,##0.0;[Red](#,##0.0)"),
Alignment = new Alignment
{
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Top,
WrapText = true,
Rotation = 45
},
};
sheet1.Cells.CreateRange("B10:D5").MergeCells();
sheet1.AutoFitColumns();
sheet1.SetColumnWidth(3, 12);
}
but when i tried to open the excel file, a message box appears as " "

The short answer is that you shouldn't be trying to create an Excel file on the server like this. There are technical issues and licensing issues of using the Excel API to do this - you can read more here http://support.microsoft.com/default.aspx/kb/257757
The technical problems may well explain why you're file is corrupt.
The better approach would be to use a library that doesn't rely on the Excel API, I listed a few in my question/answer here Reading Excel Files as a Server Process that may help you.

Use this for open Excel:
ApplicationClass excel = new ApplicationClass();
Worksheet sheet1 = Activate(excel);
//insert you'r code
Use this for save and close Excel:
excel.Visible = true;
object misValue = System.Reflection.Missing.Value;
sheet1.SaveAs(filename, XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
excel.Application.Quit();
excel.Quit();
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(excel);
excel = null;

Related

Export Chart to Excel File

I am new in C# Programming. I am creating a winform application in which I am using System.Windows.Forms.DataVisualization Chart. This chart contains multiple series. I want to export that chart data to Excel file.
To Add Data to chart I am using
chart.Series[mSeries].Points.AddXY(dt, avgData);
dt is current DateTime and the data.
So my Excel file look like
First Column is Series Name, second is DateTime and third column contain data.
So, can anyone please tell me how I can do this.
Thanks in Advance
You can refer to the following solution. First you will need to add reference to Microsoft Excel Object Library of COM. See this link on how to add. Then next step is pretty simple. You will need to add the code from the above link and replace the data which you fed in Excel with your custom data.
Here is the code shown in the link.
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i = 0; i < chart1.Series.Count; i++)
{
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "DateTime";//put your column heading here
xlWorkSheet.Cells[1, 3] = "Data";// put your column heading here
for (int j = 0; j < chart1.Series[i].Points.Count; j++)
{
xlWorkSheet.Cells[j + 2 , 2] = chart1.Series[i].Points[j].XValue;
xlWorkSheet.Cells[j + 2 , 3] = chart1.Series[i].Points[j].YValues[0];
}
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("B2", "c5");//update the range here
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
Simply replace the cells and data from the code with your custom data and viola when you click on export button it will export it for you.

How to create readonly Excel sheet using C# .net

I am creating a dynamic Excel sheet using ExcelWorksheet. I need to create a non-editable excel. ws.Cells["A1:Q12"].Style.Locked = true is not working.
Here is my code :
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/Download/Sample.xlsx");
using (ExcelPackage pck = new ExcelPackage())
{
FileInfo summaryFilePath = new FileInfo(filePath);
ExcelWorksheet ws= pck.Workbook.Worksheets.Add("Sample Page");
CreateForamters(ws);
}
}
private void CreateForamters(ExcelWorksheet ws)
{
ws.Cells["B8:L8"].Value = "SamplePage";
ws.Cells["B10:L10"].Value = DateTime.Now.ToString("MMM-yy");
ws.Cells["B11:L11"].Value = "test data........-";
ws.Cells["B8:L11"].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells["B8:L11"].Style.Font.Bold = true;
ws.Cells["B8:L11"].Style.Font.Name = "Arial";
ws.Cells["B8:L11"].Style.Font.Size = 16;
ws.Cells["B8:L11"].Style.Font.Color.SetColor(Color.Blue);
ws.Cells["B8:L11"].Style.Fill.BackgroundColor.SetColor(Color.White);
ws.Cells["B8:L11"].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
ws.Cells["B8:L8"].Merge = true;
ws.Cells["B9:L9"].Merge = true;
ws.Cells["B10:L10"].Merge = true;
ws.Cells["B11:L11"].Merge = true;
ws.Cells["A1:Q12"].Style.Locked = true;
}
Thank you all in advance for your response.
I am creating a dynamic Excel sheet using ExcelWorksheet. I need to create a non-editable excel. ws.Cells["A1:Q12"].Style.Locked = true is not working.
To create NON-Editable Cells, you have to use
ws.get_Range("A1", "Q12").Locked = true;
And then you need to protect the worksheet. Without protecting the worksheet, the .Locked command doesn't have any significance.
Here is a basic example (TRIED AND TESTED IN VS2010 + OFFICE 2010)
object misValue = System.Reflection.Missing.Value;
ws.get_Range("A1", "Q12").Locked = true;
string Password = "Sid";
ws.Protect(Password, misValue, misValue, misValue, misValue, misValue,
misValue, misValue, misValue, misValue, misValue, misValue, misValue,
misValue, misValue, misValue);
NOTE: By default all cells in Excel are locked. If you don't want to protect the rest of the cells in the sheet then remember to set their .Locked property to False.
ws.Cells.Locked = false;
and then use the above code.
if you want to save Excel WorkBook as ReadOnly Save as Below:
object misValue = System.Reflection.Missing.Value;
ExcelWorkBook.ActiveWorkbook.SaveAs(save_path, Excel.XlFileFormat.xlWorkbookNormal, misValue , misValue , True, True,XlSaveAsAccessMode.xlShared, false, false, misValue, misValue , misValue );

How to create a new worksheet in Excel file c#?

I need to create a very big Excel file, but excel file in one worksheet can contain up to 65k rows. So, i want to divide all my info into several worksheets dynamical.
This is my approximate code
//------------------Create Excel App--------------------
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(numberOfLetters);
foreach (string letter in letters)
{
xlWorkSheet.Cells[rowIndex, 1] = letter;
rowIndex++;
}
xlWorkBook.SaveAs(pathXL, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
How I can add new worksheet inside of my foreach loop and using some condition give a name to worksheet (which user can see in Excel at the bottom of the page in list)?
Some like that
foreach (string letter in letters)
{
if (letter == SOME)
{
AddNewWorksheet and give name SOME
}
xlWorkSheet.Cells[rowIndex, 1] = letter;
rowIndex++;
}
And how to save all worksheets at the end?
To add a new worksheet to the workbook use this code:
var xlSheets = xlWorkBook.Sheets as Excel.Sheets;
var xlNewSheet = (Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "newsheet";
// Uncomment a line below if you want the inserted sheet to be the last one
//xlWorkBook.Sheets.Move(After: xlWorkBook.Sheets.Count);
To save the workbook call Save() method:
xlWorkBook.Save();
This is the correct code that is given in MSDN.
Excel.Worksheet newWorksheet;
newWorksheet = (Excel.Worksheet)Globals.ThisWorkbook.Worksheets.Add(
missing, missing, missing, missing);
For more information please click the link
In General when you want to create new sheet just do :
var worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add();
knowing that you already created the workbook like below :
var workbook = excel.Workbooks.Add(Type.Missing);
You are limited to 65,000 records with .xls , but if you are "allowed" to step beyond .xls / 2003 and into 2007 and above with .xlsx you should have a lot more rows.
Side note, nothing to do with your question, but a while back I had export to excel issues with RDLC and sheet names I renamed using NPOI library, since then I started using NPOI a lot more it is free /open source and very powerful (ported from Java POI to .net NPOI) again while I say it is not really a part of what your question is I wouldn't be surprised if it had examples on doing this (no I don't work for them ) http://npoi.codeplex.com/
Here is the code I had written for renaming sheets (which ends up re-creating the sheets with another memorystream
------------------------------------------------------------
var excelHelper = new ExcelHelper(bytes);
bytes = excelHelper.RenameTabs("Program Overview", "Go Green Plan", "Milestones", "MAT and EOC", "Annual Financials", "Risk Log", "Risk & Opportunity Log", "RAIL", "Meeting Minutes");
Response.BinaryWrite(bytes);
Response.End();
------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
namespace Company.Project.Core.Tools
{
public class ExcelHelper
{
private byte[] _ExcelFile;
public ExcelHelper(byte[] excelFile)
{
_ExcelFile = excelFile;
}
public byte[] RenameTabs(params string[] tabNames)
{
byte[] bytes = null;
using (MemoryStream ms = new MemoryStream())
{
ms.Write(_ExcelFile, 0, _ExcelFile.Length);
var workBook = new HSSFWorkbook(ms, true);
if (tabNames != null)
{
using (MemoryStream memoryStream = new MemoryStream())
{
for (int i = 0; i < tabNames.Length; i++)
{
workBook.SetSheetName(i, tabNames[i]);
}
workBook.Write(memoryStream);
bytes = memoryStream.ToArray();
}
}
}
_ExcelFile = bytes;
return bytes;
}
}

Exception from HRESULT: 0x800A03EC Error while saving Excel file

I am saving data on button's click event and below is code:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
object misValue = System.Reflection.Missing.Value;
String st = System.IO.Directory.GetCurrentDirectory() + "\\A.xlsx";
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open(st, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 6;
for (i = 6; i < 10; i++)
{
xlWorkBook.SaveAs(st, XlFileFormat.xlExcel9795, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
MessageBox.Show(xlWorkSheet.get_Range("L" + #i, "L" + #i).Value2.ToString());
}
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
When I am saving it, it gives me error:
HRESULT: 0x800A03EC Error while saving Excel file
check for cell indices for sheet , starts from [1,1]
sheet.cells[0,0] will throw com error.
As I understand at Saving an Excel File Exception from HRESULT: 0x800A03EC Exception raised when arguments of method SaveAs are wrong. Please review your arguments at:
xlWorkBook.SaveAs(st1, XlFileFormat.xlExcel9795, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
I know this thread is old, but this may be of help to somebody. I had the same problem, and calling the Activate() function on the workbook fixed it for me:
yourWorkBookObject.Activate()
#Sebastian is correct in that you are calling SaveAs four times, saving to the same location without closing. This isn't going to work, you need to first of all move this out of the loop. But looking at your code more closely, you aren't changing anything in the workbook, so there is no need to save, and if you did change something, you would be better calling Save instead of SaveAs. As well as this, you are specifying ReadOnly as true when you are opening the workbook, so attempting to call save in any capacity isn't going to work.
Finally, if you are using >= C# 4, you can use optional parameters, so all of those misValue's are unnecessary. I tidied up your code below:
using Excel = Microsoft.Office.Interop.Excel;
var st = System.IO.Directory.GetCurrentDirectory() + "\\A.xlsx";
var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open(st);
var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.Item[1];
for (var i = 6; i < 10; i++)
{
MessageBox.Show(xlWorkSheet.Range["L" + #i, "L" + #i].Value2.ToString());
}
//make some changes here
xlWorkBook.Save();
xlWorkBook.Close();
xlApp.Quit();
I had the same error while saving the Excel file line.
xlWorkBook.SaveAs(st);
I found out the folder name has been changed by someone cause an issue for me to save the file to the given file location at "st". I hope this helps someone to check first.
In case anyone else makes the same mistake as me, in my case it was due to the filename used to save the excel file. It had an illegal character in the name "/" which was causing this 0x800A03EC Error with no details at all.
So before dealing with permissions make sure that the path exists AND that the filename is legal.

Format cell in an excel sheet using interop

I need to add borders to excel cells in Automatic colour using c# language. Given below is the coding that i use. But it doesn't add any borders to the cell. Can you please let me know what i have done wrong here:
i'm not getting any border designing functionalities when i try to specify border styles to cells:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlWorkBook = xlApp.Workbooks.Open(textBox1.Text, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
DataGridViewCell cell = dataGridView1[j, i];
xlWorkSheet.Cells["19", "I"] = "Availablility";
xlWorkSheet.Cells[i + 20, j + 9] = cell.Value;
xlWorkSheet.Cells.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
}
}
try this.Not posting the entire code
Excel.Worksheet oSheet;
Excel.Range oRange;
oRange = oSheet.get_Range("Q3", "Q40");
oRange.Font.Color= System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
oRange.Cells.Borders.Color=System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
If you are just trying to put a border around the table you've created, once you've built the whole table try:
xlWorksheet.Cells ["19", "I"].CurrentRegion.BorderAround(xlContinuous, xlMedium, xlColorIndexAutomatic);
Your code is currently trying to put a border around the whole worksheet
I think you need to select cells first. The following code works for me:
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelInteropDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application excel = new Excel.Application();
excel.Workbooks.Add();
excel.Visible = true;
excel.ActiveWorkbook.ActiveSheet.Range("a1").EntireRow.Select();
excel.Selection.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium,
Excel.XlColorIndex.xlColorIndexAutomatic,
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(79, 129, 189)));
}
}
}
Update 2012-10-23:
After some discussion in the comments and the original post has been updated, the problem became all about IntelliSense, instead of the syntax of Excel Interop.
As you need to add just border so try the following code. it works for me.
private void AllBorders(Excel.Borders borders)
{
borders.Color = System.Drawing.Color.Black;
}
//Call the function now.
AllBorders(activeWorkSheet.get_Range(Cell1: "A1", Cell2: "lastcellname").Cells.Borders);
And If you want to set border just LEFT/RIGHT/TOP/Bottom then use the following code.
borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlMedium;
borders[Excel.XlBordersIndex.xlEdgeRight].Color = System.Drawing.Color.Black;
Set the edges according to your requirement I have enabled the border for RIGHT side only with "xlEdgeRight"

Categories