Insert into Existing excel file using EPP on C# - c#

I want to insert value on my excel ,but i have a problem when i run my application, its create a new file excel ,doesnt insert value into existing file,
using (ExcelPackage excel = new ExcelPackage())
{
excel.Workbook.Worksheets.Add("Worksheet1");
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
excel.SaveAs(excelFile);
I want my Program insert into existing file ,not create a new one,
how i can solve this?

The EPPlus Wiki Getting Started covered this exact scenario.
FileInfo excelFile = new FileInfo(#"E:\ExcelTest.xls");
using (ExcelPackage excel = new ExcelPackage(excelFile))
{
// Target a worksheet
var worksheet = excel.Workbook.Worksheets["Worksheet1"];
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[2, 1].Value = "ID";
excel.Save();
}

Related

How to copy worksheet data and style with EPPlus C#?

I am saving data to a new worksheet with EPPlus. But it doesn't copy the styles of the worksheet I use as a template. How can I do that?
As seen in the picture, the cell height of the template is 25, while the cell height of the new worksheet I created using the template is 18. I want the cell height in the new worksheet to be 25 as well.
My code is here..
FileInfo template = new FileInfo(path + #"\Template\template.xlsx");
using (ExcelPackage package = new ExcelPackage(template))
{
FileInfo newFile = new FileInfo(fileCheck);
using(ExcelPackage pack = new ExcelPackage(newFile))
{
ExcelWorksheet ws0 = package.Workbook.Worksheets[0];
ws0.Cells["A8"].Value = texedit2.Text;
pack.Workbook.Worksheets.Add("Sheet2", ws0);
pack.SaveAs(newFile);
}
}
Is there any other solution?
The best way I've found to do this loop through each row in the new worksheet and manually set the height to match the corresponding row in the template.
ExcelWorksheet ws0 = package.Worksheets[0];
ExcelWorksheet newWorksheet = pack.Workbook.Worksheets.Add("Sheet2", templateWorksheet);
for(int i = 0; i < ws0.Dimensions.Row + 1; i++)
{
newWorksheet.Rows[i].CustomHeight = true;
newWorksheet.Rows[i].Height = ws0.Rows[i].Height;
}

Downloaded Excel showing blank after Microsoft's security update

I have exported table values to excel file through GridView using below C# code.
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition","attachment;filename="+filename+".xls");
It was working well until recent security update from Microsoft [security update for microsoft excel 2010 kb3115322].
After the update, I am unable to view the content of Excel file. It is showing blank excel.
After uninstalling the update I can view the Excel but I need a solution through C# code.
Thanks in advance.
Yes due to Microsoft new security update issue is rising to current excel files format. So for solving and for a quick solution you should make csv (comma separated file) instead of xls so excel application will open the csv by ',' seperator.
Note : I faced this issue in my Php application , and I solved by making xls file with PHPExcel library.I hope you may find something like PHPExcel for C# as well.
Thanks. Feel free to comment.
I run into the same problem. My solution was to rewrite all Excel exports with ExcelPack. And I used XLSX and no longer XLS.
just in case rewriting is an option for you.
https://excelpackage.codeplex.com/
ExcelPackage package = new ExcelPackage();
ExcelWorksheet ws = package.Workbook.Worksheets[1];
//header
ws.Cells[1, 1].Value = "Column1";
ws.Cells[1, 2].Value = "Column2";
ws.Cells[1, 3].Value = "Column3";
ws.Cells[1, 4].Value = "Column4";
ws.Cells[1, 5].Value = "Column5";
//content
int i = 1;
foreach (Item item in list)
{
i++;
ws.Cells[i, 1].Value = item.Prop1;
ws.Cells[i, 2].Value = item.Prop2;
// format datetime
ws.Cells[i, 3].Value = item.Prop3.ToString("yyyy-MM-dd");
ws.Cells[i, 4].Value = item.Prop4;
ws.Cells[i, 5].Value = item.Prop5;
}
using (var memoryStream = new MemoryStream())
{
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("content-disposition", $"attachment; filename=Filename.xlsx");
package.SaveAs(memoryStream);
memoryStream.WriteTo(response.OutputStream);
response.Flush();
response.End();
}

Generate sheet separated excel with GridView in MVC web enviroment

I use the following code, and I'm wondering if I can somehow make this a sheet separated excel file with each row in its own sheet.
DataTable dt = new DataTable();
SqlConnection objcon = new SqlConnection(connectionString);
string sql = "SELECT * FROM table";
SqlDataAdapter objda = new SqlDataAdapter(sql, objcon);
objda.Fill(dt);
GridView gvreport = new GridView();
gvreport.DataSource = dt;
gvreport.DataBind();
string date = DateTime.Now.ToString("yyyy_MM_dd_HHmmss");
string fileName = string.Format("TheFilename_{0}.xls", date);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvreport.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return null;
I know that this doesn't exactly generate a real excel file but rather tricks the browser to create one. Which is probably why its a bit more complicated to make advanced excel files.
I've already tried with things like setting a max amount of rows per gridview page and so on.
Are there any way of doing this, or in general create an excel file in another way that allows me to do this. Without needing Windows office or similar installed.
Thank you for your time.
I would use something like OpenXML. I'm guess the reason your creating the excel file on the fly is because you don't want to use interop objects because they are too heavy and bulky. However you still need the flexibility to manipulate objects. I would look at the OpenXML library as it contains many of the manipulations that your looking for the code would look something like below to get you started. In the above link you'll notice there is an example for mvc. Which really doesn't change the underlying code much.
using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workBookPart = spreadSheetDocument.AddWorkbookPart();
WorksheetPart worksheetPart = workBookPart.AddNewPart<WorksheetPart>();
WorkbookStylesPart workBookStylesPart = workBookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet stylesheet = new CustomStyleSheet();
stylesheet.Save(workBookStylesPart);
string relId = workBookPart.GetIdOfPart(worksheetPart);
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet();
var columns = CreateColumns();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet { Name = "mySheet", SheetId = 1, Id = relId };
sheets.Append(sheet);
worksheet.Append(columns);
SheetData sheetData = CreateSheetData();
worksheet.Append(sheetData);
workbook.Append(sheets);
worksheetPart.Worksheet = worksheet;
worksheetPart.Worksheet.Save();
spreadSheetDocument.WorkbookPart.Workbook = workbook;
spreadSheetDocument.WorkbookPart.Workbook.Save();
//Now I want to add an empty sheet
sheet = new Sheet { Name = "mySheet2", SheetId = 2, Id = relId };
sheets.Append(sheet);
spreadSheetDocument.WorkbookPart.Workbook.Save();
spreadSheetDocument.Close();
}

how to write data to Excel without changing the current format

I am trying to overwrite data in excel sheet. The way I do it is by deleting the content from the the sheet and then writing range of data. The problem is when I write the data it deletes the cell format and then places my numbers as text.
is there a way to keep the format which the user has defined so when I write data it uses the same format?
You can Use the Microsoft.Office.Interop.Excel dll file. Add it in your project reference and in your Code as Using using Excel = Microsoft.Office.Interop.Excel;
Then check the below code. Also to you this dll there should be Microsoft Excel Installed in the machine where this code is going to run.
Excel.Application excel = new Excel.Application();
excel.DisplayAlerts = false;
excel.Workbooks.Add();
Excel.Worksheet worksheet = excel.ActiveSheet;
int rowIndex = 2 ;
worksheet.Cells[1, "A"] = "List Title";
worksheet.Cells[1, "B"] = "Item Count";
Console.WriteLine("Copying the contents to Excel");
foreach (var list in listCollection)
{
worksheet.Cells[rowIndex, "A"] = list.Title;
worksheet.Cells[rowIndex, "B"] = list.ItemCount;
rowIndex++;
//Console.Write("List Title: {0}", list.Title);
//Console.WriteLine("\t"+"Item Count:"+list.ItemCount);
}
string fileName = string.Format(#"C:\FileName.xlsx");
worksheet.SaveAs(fileName);
Console.WriteLine("Export Completed");
Console.ReadLine();
excel.Quit();
GC.Collect();

opening .xlsx in office 2003

I have created a .xlsx using openxml.
I am not able to open this file in office 2003.. I have also tried using compatibility pack but still the file does not open. What can be done if i need to generate .xlsx that can be opened in office 2003 as well.
Code i am using to generate .xlsx is :
public static void HelloWorldXlsx(string docName)
{
SpreadsheetDocument package = SpreadsheetDocument.Create(docName, SpreadsheetDocumentType.Workbook);
package.AddWorkbookPart();
package.WorkbookPart.Workbook = new Workbook();
WorksheetPart wspart = package.WorkbookPart.AddNewPart<WorksheetPart>();
Cell cell = new Cell();
cell.DataType = CellValues.InlineString;
cell.InlineString = new InlineString(new DocumentFormat.OpenXml.Spreadsheet.Text("Hello World!"));
wspart.Worksheet = new Worksheet(new SheetData(new Row(cell)));
wspart.Worksheet.Save();
package.WorkbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet();
sheet.Id = package.WorkbookPart.GetIdOfPart(wspart);
sheet.SheetId = 1;
sheet.Name = "Hello !";
package.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild<Sheet>(sheet);
package.WorkbookPart.Workbook.Save();
package.Close();
}
Thanks for suggestion. I got the answer to my question .. I had not set cellReference property of Cell in my code.

Categories