I am working with closedXML in C#. I'm importing an Excel. It is importing correct data but auto-format rows and headers every time. I need to compare data of Excel file in C# with a standard template. Due to formatting, it doesn't match. Can somebody help me to remove theme/ autoformat from Excel in C#?
DataTable dt = _excecuteProcedure.ToDataTable(filteredAmenities);
using(XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt);
ws.Tables.FirstOrDefault().ShowAutoFilter = false;
ws.Name = "Sheet1";
using(MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Template.xlsx");
}
}
Related
I am fetching an Excel file from ftp and getting that file in a memory stream. I have to read that file from memory stream. I tried through Excel Interop but it is not accepting memory stream as a parameter in
xlWorkBook = xlApp.Workbooks.Open(strm, 0, true, 5, "", "", true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
According to system requirement that I cannot save that file temporary; because I am using Azure web jobs for Console application deployment. Is there any way to read file from memory stream or can I convert that memory stream into an array of string?
I can suggest you to use ExcelDataReader 3.1.0 to read data from an Excel file.
Now you can use that MemoryStream in ExcelReader like this:
Note that reader of old Excel files -.xls- is different form newer files -.xlsx-.
var excelReader = originalFileName.EndsWith(".xls")
? ExcelReaderFactory.CreateBinaryReader(stream)
: ExcelReaderFactory.CreateOpenXmlReader(stream);
If you want to extract a string from your MemoryStream you can use a StreamReader:
var streamReader = new StreamReader(memoryStream);
var stringResult = streamReader.ReadToEnd();
If you want to work over a FileStream you can copy your MemoryStream to it like this:
memoryStream.CopyTo(fileStream);
Also EasyXLS accepts streams, including MemoryStream.
I don't know if you need only data in cells from Excel, or other information, but the code bellow is only for data:
ExcelDocument excelWorkbook = new ExcelDocument();
DataSet ds = excelWorkbook.easy_ReadXLSActiveSheet_AsDataSet(memoryStream);
More details about reading Excels, you can find at this location:
https://www.easyxls.com/manual/FAQ/read-excel-file-in-dot-net.html
There is no MS Office present in the Azure Webjob, so we cannot use Microsoft.Office.Interop Dll in the Azure Webjob. Please have a try to use DocumentFormat.OpenXml to do that. The following is the demo code from the official document. I also find another tutorials about how to Read and Write Microsoft Excel with Open XML SDK.
public static void OpenAndAddToSpreadsheetStream(Stream stream)
{
// Open a SpreadsheetDocument based on a stream.
SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(stream, true);
// Add a new worksheet.
WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new Worksheet(new SheetData());
newWorksheetPart.Worksheet.Save();
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
spreadsheetDocument.WorkbookPart.Workbook.Save();
// Close the document handle.
spreadsheetDocument.Close();
// Caller must close the stream.
}
I have a import functionality in my asp.net application where right now I am able to import only .xls files. I want to make the import functionality working so that it should import .csv file. But I am getting this errorsee the error
Can some one please help me in code, how can I import .csv file.
ImportHandler.cs
private IEnumerable<PermanentFlight> ExportPermanentFlightsXlToEf(string fileName)
{
Log.Info("Exporting records from Excel to PF Entity starts.");
HSSFWorkbook workBook;
using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
workBook = new HSSFWorkbook(file);
}
var workSheet = workBook.GetSheetAt(0);
var rowIdx = 1;
var scheduleName = string.Empty;
var list = new List<PermanentFlight>();
I have problem with export dataset into xlsx. My code:
DataSet freeTable = new DataSet();
freeTable = FoxDal.Instance.freeTable;
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(freeTable.Tables[0], "sheet1");
wb.SaveAs(#"E:\test5.xlsx");
While running code VS give's me prompt ( asking me where is XLReentrantEnumerableSet.cs) if i dont choose it VS throw exception System.OutOfMemoryException. Im using ClosedXML. There are some attached libraries for this framework? With small tables my code working corectly.
I change framework to EPPlus and now i can convert large files.
My new code:
DataSet freeTable = new DataSet();
freeTable = FoxDal.Instance.freeTable;
FileInfo fileInfo = new FileInfo(#"E:\Test.xlsx");
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("table");
ws.Cells["A1"].LoadFromDataTable(freeTable.Tables[0], true);
pck.SaveAs(fileInfo);
}
I am creating an Excel file using the EPPlus library. When I create file and open up the file, the following pop up message shows:
We found a problem with some content in 'ExcelDemo.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes
I am using following code
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells[1, 2].Value = "Excel Download";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Is there problem in my code or is this an Excel issue?
In my case the problem was in calling
package.Save();
and using
Response.BinaryWrite(package.GetAsByteArray());
at the same time.
When you call package.GetAsByteArray() it perfoms following operations internally:
this.Workbook.Save();
this._package.Close();
this._package.Save(this._stream);
So, calling package.Save two times leads to this error when opening in Excel.
At the start, you need to add in a:
Response.Clear();
Then at the end add a
Response.End();
I will share my solution. I am using a template excel file and then create new excel from it.
Receiving the same error. My code was
using (Stream newFileStream = File.Open(this.tempFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
using (Stream originalFile = File.Open(this.initialFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (ExcelPackage excelPackage = new ExcelPackage(newFile, template))
{
// ... Do work here
}
I had to change code to:
FileInfo intialInfo = new FileInfo(this.initialFilePath);
FileInfo tempFileInfo = new FileInfo(this.tempFilePath);
using (ExcelPackage excelPackage = new ExcelPackage(tempFileInfo, intialInfo))
{
//... Do work here
}
Also I am using ASP MVC and the response is:
byte[] result = exporter.GetBytesFromGeneratedExcel();
return this.File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Test.xlsx");
In my case, problem was data table name which I did not set earlier.
Try this one,
dt.TableName = "ExcelSheet1";
I was having this problem because I was writing a string larger than 32,767 characters into a single cell. Excel doesn't like this, but EPPlus won't stop you from doing it.
My code was updated... and was getting the same error.... and I finally found my solution
Original Code:
public static void ExportToExcel(HttpContext ctx, DataTable tbl, string fileName)
{
try
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(fileName);
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
int rowCount = tbl.Rows.Count;
List<int> dateColumns = new List<int>();
foreach (DataColumn d in tbl.Columns)
{
if (d.DataType == typeof(DateTime))
dateColumns.Add(d.Ordinal + 1);
}
CultureInfo info = new CultureInfo(ctx.Session["Language"].ToString());
foreach (int dc in dateColumns)
ws.Cells[2, dc, rowCount + 1, dc].Style.Numberformat.Format = info.DateTimeFormat.ShortDatePattern;
//Write it back to the client
ctx.Response.Clear();
ctx.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xlsx");
ctx.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ctx.Response.Buffer = false;
ctx.Response.BufferOutput = false;
ctx.Response.BinaryWrite(pck.GetAsByteArray());
ctx.Response.End();
}
}
catch (Exception EX)
{
ctx.Response.Write(EX.ToString());
}
}
Code update:
catch (Exception EX)
{
if (!(EX is System.Threading.ThreadAbortException))
{
ctx.Response.Write(EX.ToString());
}
}
IT WORKED!
A solution I came up with was just returning the file object in the controller. The first argument should be the byte array (file), the second argument is the content type, and the last argument is the filename (in my case "report.xlsx").
return File(file, "application/octet-stream", fileName);
Hope this helped.
I'm trying to create an excel file and make that available as download. But i have some trouble with the download part.
I'm using EPPlus to create an xml file. I've got that working. But just local. I'm not sure how to force the download of the file.
This is my code:
public Stream GetXlsxDocument(IQueryable data)
{
const string sheetName = "Sheet1";
var localFile = new FileInfo(#"C:\test2.xlsx");
var file = new FileInfo("test2.xlsx");
// Used for local creation
//ExcelPackage p = new ExcelPackage();
MemoryStream stream = new MemoryStream();
using (ExcelPackage p = new ExcelPackage(stream))
{
p.Workbook.Worksheets.Add("Sheet1");
ExcelWorksheet ws = p.Workbook.Worksheets[1];
ws.Name = sheetName;
ws.Cells.Style.Font.Size = 11;
ws.Cells.Style.Font.Name = "Calibri";
ws.SetValue(1, 1, "aaa"); // Test data
// Used for local creation
//p.SaveAs(localFile);
p.SaveAs(stream);
}
return stream;
}
Like i said before. Creating the xlsx file locally on my C:\ disk works. But how can i force the download of the created xlsx file?
Right now its giving me an xlsx file of 0 bytes. I'd need to return a stream which isn't empty. Anyone any idea how i can do this..??
rewind it:
stream.Position = 0;
return stream;