I'm using EPPlus in a web application with C#. I need to read an Excel file and check its format, I tried it doing the same as this article (How do I get partial cell styling in excel using EPpplus?), and actually all format properties were ok (bold, italic, color...), but the one that I really need is to check the strike
text property and it is always set to false.
Here is an answer just so the question doesnt hang out there:
[TestMethod]
public void Strike_Format_Test()
{
//http://stackoverflow.com/questions/30517646/how-to-apply-strike-formatting-using-epplus
var existingFile = new FileInfo(#"c:\temp\StrikeFormat.xlsx");
using (var pck = new ExcelPackage(existingFile))
{
var wb = pck.Workbook;
var ws = wb.Worksheets.First();
var cell = ws.Cells["A1"];
Console.WriteLine(cell.Style.Font.Strike);
}
}
Related
I am trying to use OpenXML to programmatically set an Excel workbook to visible, but am fairly new to C# and am not sure how to do that.
We are using a 3rd party application that stores Office documents and I'm tasked with reporting. One of the many strange things it does is compresses documents before saving them and sets Excel Workbook visibility to false in the database record.
According to the documentation there is the function that should do that:
public DocumentFormat.OpenXml.EnumValue<DocumentFormat.OpenXml.Spreadsheet.VisibilityValues> Visibility { get; set; }
How do I translate that into a working C# example? I don't have much so far:
using (MemoryStream mem = new MemoryStream())
{
mem.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument rptTemplate = SpreadsheetDocument.Open(mem, true))
{ // the next line doesn't work
rptTemplate.WorkbookPart.Workbook.WorkbookProperties.SetAttribute(VisibilityValues = visible)
rptTemplate.WorkbookPart.Workbook.Save();
rptTemplate.SaveAs(filePathName);
}
}
first of all you need to get WorkbookView of your workbook, so
var workBookView = workbookpart.Workbook.Descendants<WorkbookView>().FirstOrDefault();
and then you can set desired visibility :
workBookView.Visibility = VisibilityValues.Hidden;
if you are creating spreadsheet document you should create workBookView before you can use it,like below:
spreadsheetDocument.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
I got Excel xlsx document with hyperlinks.
Hyperlinks have adresses and subaddresses (that's the way VBA call Html fragments, all after # sign)
Epplus library has Hyperlink property for every cell, but it has only first part of html address, so instead of
stackoverflow.com#footer
I got:
stackoverflow.com
Is there any way to read the html fragment part with this library ?
Code for reading hyperlinks via epplus:
FileInfo xlsxFile = new FileInfo(_filePath);
using (ExcelPackage pck = new ExcelPackage(xlsxFile))
{
var wb = pck.Workbook;
if (wb == null)
return null;
var ws = wb.Worksheets.FirstOrDefault();
ExcelRange er = ws.Cells[0,0];
var hyperlink = er.Hyperlink;
It seems to be an issue with the way excel store hyperlinks and the way Epplus reads them. Excel stores the hyperlinks both in the worksheet itself as well as the relationship file for the worksheet which is a file that stores any kind of cross referencing between workbook parts (worksheets, styles, strings, etc). This all has to do with the structure of the an xlsx file which is xml based off of the OpenOffice XML standard: OpenOffice XML Info
So the problem is Epplus is relying on that relationship file which does not contain the fragment while the `hyperlink' node in the worksheet xml does. You can see all of this in its gory detail if you open up the xlsx file as a zip file by renaming it.
So, the short answer is you are forced to use the `.Value' of the cell object. Not as clean but it will work. For example, if I create a cell like this:
with this code:
var fi = new FileInfo(#"c:\temp\Html_Fragment.xlsx");
using (var pck = new ExcelPackage(fi))
{
var wb = pck.Workbook;
var ws = wb.Worksheets.FirstOrDefault();
ExcelRange er = ws.Cells[1,1];
var hyperlink = er.Hyperlink;
Console.WriteLine(er.Value);
Console.WriteLine("{{Value: {0}, Hyperlink: {1}}}", er.Value, er.Hyperlink.AbsoluteUri);
}
Gives this:
{
Value: https://msdn.microsoft.com/en-us/library/aa982683(v=office.12).aspx#Anchor_3,
Hyperlink: https://msdn.microsoft.com/en-us/library/aa982683(v=office.12).aspx
}
I have a C# data processing application which uses EPPlus to write the final results into an excel sheet. The background color of the rows are changed based on what the data on that row signifies. Time was never an issue as I only dealt with files that were below <100MB before. However, as my requirements have changed and the files get larger, I have noticed that.. just coloring makes my application 60% slower. Removing coloring makes the application significantly faster. The snippet below is an example of the code which I use to color the data to make it visually distinguishing. I'm no expert at EPPlus but is there a way, this can be optimized to make my application faster? Or are there any better ways for me to make the rows visually distinct for the people who will end up looking at the data? Any help will be appreciated!
if (data[4] == "3")
{
// color the type 3 messages here
var fill1 = cell1.Style.Fill;
fill1.PatternType = ExcelFillStyle.Solid;
fill1.BackgroundColor.SetColor(Color.LightGray);
}
if (data[4] == "4")
{
var fill1 = cell1.Style.Fill;
fill1.PatternType = ExcelFillStyle.Solid;
fill1.BackgroundColor.SetColor(Color.BlanchedAlmond);
}
EDIT:
This is the code I use to copy the template and write the excel data into the new worksheet. p is an Excel Package which I convert to a byte Array before writing to the excel file.
Byte[] bin = p.GetAsByteArray();
File.Copy("C:\\Users\\mpas\\Desktop\\template.xlsx", "C:\\Users\\mpas\\Desktop\\result.xlsx");
using (FileStream fs = File.OpenWrite("C:\\Users\\mpas\\Desktop\\result.xlsx")) {
fs.Write(bin, 0, bin.Length);
}
Styling is much faster in EPPlus, and most Excel APIs, if you use named styles. Assign and use the style to cell in EPPlus like this ...
internal static string YourStyleName = "MyStyle";
ExcelNamedStyleXml yourStyle = excel.Workbook.Styles.CreateNamedStyle(YourStyleName);
yourStyle.Style.Font.Color.SetColor(Color.DarkRed);
yourStyle.Style.Fill.PatternType = ExcelFillStyle.Solid;
yourStyle.Style.Fill.BackgroundColor.SetColor(Color.LemonChiffon);
// ...
sheet.Cells[sourceRange].StyleName = YourStyleStyleName
Here is code to open an existing file.
FileInfo AddressList = new FileInfo("c:\test\test.xlsx");
// Open and read the XlSX file.
try
{
using (ExcelPackage package = new ExcelPackage(AddressList))
{
// Get the work book in the file
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
// Get the first worksheet
//ExcelWorksheet Worksheet = workBook.Worksheets.First();
var worksheet = package.Workbook.Worksheets[1];
I am writing some report in csv ...so for the best visibility i have to write some data in bold style and some data in different color while writing data into csv..i am using below code for writing in csv ..
FileInfo outtxt = new FileInfo(filename);
// StreamWriter logline = outtxt.AppendText();
// initialiseStream();
StreamWriter logline = new StreamWriter(fs);
if (f == 0)
{
logline.WriteLine("sometext");
}
So how can we format this.
Urgent or not:
A .csv (Commas Separated Values) is piure text file, it contains fields separated by , or ;.
It is not possible to include any formatting in these files.
As others have pointed out, .csv is just a simple text file but you can generate .xlsx files using other libraries available in nuget.
In my opinion Epplus is a really easy to use example.
If you install this package then the following should give you an example you can use to get started:
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication9
{
class Program
{
static void Main(string[] args)
{
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("MySheet");
ws.Cells["A1"].Value = "Some Bold Text";
ws.Cells["A1"].Style.Font.Bold = true;
ws.Cells["A2"].Value = "Some blue text";
ws.Cells["A2"].Style.Font.Color.SetColor(Color.Blue);
ws.Cells["A3"].Value = "Some Large Text";
ws.Cells["A3"].Style.Font.Size = 22;
ws.Cells["A3"].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Red);
ws.Row(3).Height = 23;
ws.Column(1).AutoFit();
package.SaveAs(new System.IO.FileInfo(#"C:\Temp\example.xlsx"));
}
}
}
}
I guess what your are talking about is formatting in excel while displaying the .csv file. CSV is just a plain text file mostly comma separate.
If you want to format excel, take a look at Open XML
You have to create some styles to display in bold and with colors.It's a bit painful route. If you want easy , you might want to take a look at Closed XML library. This one does all the hard work for you and you just have to call few methods to get your work done.
You can use EasyXLS Excel library to write both Excel or CSV file, but the CSV file cannot contain formatting, since is just a plain text file format.
To write Excel file use this code sample:
ExcelDocument workbook = new ExcelDocument(1);
ExcelTable tableData = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
tableData.easy_getCell(0,0).setValue("sometext");
workbook.easy_WriteXLSFile(filename);
To format the cell use this sample code:
ExcelStyle xlsStyle = new ExcelStyle();
xlsStyle.setBold(true);
xlsStyle.setForeground(Color.DarkGray);
tableData.easy_getCell(0,0).setStyle(xlsStyle);
For more details about formatting check this link:
http://www.easyxls.com/manual/basics/format-excel-cells.html
I am using the following bit of code:
var assembly = Assembly.GetExecutingAssembly();
Stream streamToTemplete=assembly.GetManifestResourceStream("DailyAuction.xltx");
Stream streamToOutput = assembly.GetManifestResourceStream("dailyAuctionEmail.xls");
//using (ExcelPackage excelPackage = new ExcelPackage(newFile, templateFile))
using(streamToTemplete)
using (streamToOutput)
{
using (ExcelPackage excelPackage = new ExcelPackage(streamToOutput, streamToTemplete))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["Daily Auction"];
int startRow = 4;
int row = startRow;
foreach (DailyEmail dailyEmail in listDailyEmail) //iterate through all the rows in the list
{
worksheet.Cells[row, 1].Value = dailyEmail.As_At.ToString("dd-MMM-yy HH:mm");
worksheet.Cells[row, 2].Value = dailyEmail.Auction_Date.ToString("dd-MMM-yy");
}
excelPackage.Save();
}
}
var attachment = new Attachment(streamToOutput, new ContentType("application/vnd.ms-excel"));
However, I am getting an error saying streamToTemplate & streamToOutput are null. What seems to be the problem? Also, will the rest of the code work?
Check the properties on both the Excel files. Build Action should be 'Embedded Resource'.
Also, the string that you are providing to GetManifestResource stream looks too simple. The string should be:
<defaultNamespace>.<folderName>.<fileName> MSDN Article
This answer suggests calling the GetManifestResourceNames, then using the debugger to take a look at the resource names. Seems a good way to go while you're finding your way.