Convert datatable to .xlsx format - c#

public static void ExportToExcel(DataTable dtExcel, string fileName)
{
string attachment = "attachment; filename=" + fileName + ".xlsx";
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", attachment);
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
//System.Web.HttpContext.Current.Response.ContentType = "application/excel";
//System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//System.Web.HttpContext.Current.Response.ContentType = string.Empty;
string tab = "";
foreach (DataColumn dc in dtExcel.Columns)
{
System.Web.HttpContext.Current.Response.Write(tab + dc.ColumnName);
tab = "\t";
}
System.Web.HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in dtExcel.Rows)
{
tab = "";
for (i = 0; i < dtExcel.Columns.Count; i++)
{
System.Web.HttpContext.Current.Response.Write(tab + dr[i].ToString());
tab = "\t";
}
System.Web.HttpContext.Current.Response.Write("\n");
}
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
Above code snippet generate only .xls format .If i change response time and File-name extension to .xlsx it does not work .Is there any other approach to do the same.
As per suggestion i have changed approach and generating .xlsx using openxml library.
But it throws error Unable to determine the identity of domain while generating large xlsx file.Please help
public static void ExportToexcel(DataTable dtExcel, string fileName)
{
System.Web.HttpContext.Current.Response.ClearContent();
OpenXMLOffice openxmloffice = new OpenXMLOffice();
MemoryStream msXML = openxmloffice.DataTableToMemoryStream(dtExcel);
msXML.Seek(0, SeekOrigin.Begin);
msXML.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=DataTable.xlsx");
System.Web.HttpContext.Current.Response.StatusCode = 200;
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}

The fastest and most reliably method is to use a library like epplus, whcih even has methods like toDatatTable() and FromDataTable()
http://epplus.codeplex.com/

Related

Get contents from each page in Crystal Report viewer and export it to a pdf

I need to get the content inside each page of a crystal report viewer and export it to a pdf file so that each page becomes a separate pdf and need to zip them.
Now i'm using DotNetZip dll for this.That's fine.
The issue is that i need to get contents of each page.Please Help..Below is few lines of code
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int i = 1;
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if(PageCount >= 1){
using (ZipFile zip = new ZipFile())
{
for (i = 1; i <= PageCount; i++){
var re = report.ExportToStream(ExportFormatType.PortableDocFormat);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, re);
}
zip.Save(Response.OutputStream);
}
}
Finally i found the answer!!..It may help someone in future.
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if (PageCount >= 1)
{
using (ZipFile zip = new ZipFile())
{
for (int i = 1; i <= PageCount; i++)
{
PdfRtfWordFormatOptions pdfRtfWordOpts = ExportOptions.CreatePdfRtfWordFormatOptions();
DiskFileDestinationOptions destinationOpts = ExportOptions.CreateDiskFileDestinationOptions();
ExportRequestContext req = new ExportRequestContext();
pdfRtfWordOpts.FirstPageNumber = i;
pdfRtfWordOpts.LastPageNumber = i;
pdfRtfWordOpts.UsePageRange = true;
ExportOptions CrExportOptions = report.ExportOptions;
{
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.FormatOptions = pdfRtfWordOpts;
req.ExportInfo = CrExportOptions;
}
Stream s = report.FormatEngine.ExportToStream(req);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, s);
}
zip.Save(Response.OutputStream);
}
}

.Net Core: Reading data from CSV & Excel files

Using .net core & c# here.
I have a UI from which user can upload the Excel or CSV files. Once they upload this goes to my web api which handles the reading of the data from these files and returns json.
My Api code as:
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file)
{
JArray data = new JArray();
using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
//Process, read from excel here and populate jarray
}
return Ok(data );
}
In my above code I am using EPPlus for reading the excel file. For excel file it works all fine but it cannot read csv file which is the limitation of EPPlus.
I searched and found another library CSVHelper: https://joshclose.github.io/CsvHelper/ The issue with this is it does vice versa and can read from CSV but not from Excel.
Is there any library available which supports reading from both.
Or would it be possible use EPPlus only but convert uploaded CSV to excel on the fly and then read. (please note I am not storing the excel file anywhere so cant use save as to save it as excel)
Any inputs please?
--Updated - Added code for reading data from excel---
int rowCount = worksheet.Dimension.End.Row;
int colCount = worksheet.Dimension.End.Column;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
{
var rowValue = worksheet.Cells[row, col].Value;
}
}
//With the code suggested in the answer rowcount is always 1
You can use EPPLus and a MemoryStream for opening csv files into an ExcelPackage without writing to a file. Below is an example. You may have to change some of the the parameters based on your CSV file specs.
[HttpPost("upload")]
public async Task<IActionResult> FileUpload(IFormFile file)
{
var result = string.Empty;
string worksheetsName = "data";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = ',';
format.TextQualifier = '"';
using (var reader = new System.IO.StreamReader(file.OpenReadStream()))
using (ExcelPackage package = new ExcelPackage())
{
result = reader.ReadToEnd();
ExcelWorksheet worksheet =
package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(result, format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
}
}
Here's using Aspose, which is unfortunately not free, but wow it works great. My API is using the streaming capability with Content-Type: multipart/form-data rather than the IFormFile implementation:
[HttpPut]
[DisableFormValueModelBinding]
public async Task<IActionResult> UploadSpreadsheet()
{
if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
{
return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
}
var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, HttpContext.Request.Body);
var section = (await reader.ReadNextSectionAsync()).AsFileSection();
//If you're doing CSV, you add this line:
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV);
var workbook = new Workbook(section.FileStream, loadOptions);
Cells cells = workbook.Worksheets[0].Cells;
var rows = cells.Rows.Cast<Row>().Where(x => !x.IsBlank);
//Do whatever else you want here
Please try with below code
private string uploadCSV(FileUpload fl)
{
string fileName = "";
serverLocation = Request.PhysicalApplicationPath + "ExcelFiles\\";
fileName = fl.PostedFile.FileName;
int FileSize = fl.PostedFile.ContentLength;
string contentType = fl.PostedFile.ContentType;
fl.PostedFile.SaveAs(serverLocation + fileName);
string rpath = string.Empty, dir = string.Empty;
HttpContext context = HttpContext.Current;
string baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + '/';
try
{
rpath = serverLocation + fileName;//Server.MapPath(dir + fileName);
using (Stream InputStream = fl.PostedFile.InputStream)
{
Object o = new object();
lock (o)
{
byte[] buffer = new byte[InputStream.Length];
InputStream.Read(buffer, 0, (int)InputStream.Length);
lock (o)
{
File.WriteAllBytes(rpath, buffer);
buffer = null;
}
InputStream.Close();
}
}
}
catch (Exception ex)
{
lblSOTargetVal.Text = ex.Message.ToString();
}
return rpath;
}
Use the Open XML SDK package and add insert working solution for it.

Epplus how to remove spaces into my excel & resx file

I'm starting to learn c # and Windows form. I create an application that transforms a resx (XML) file into an Excel.
All my code works, my Excel file is created and I can convert it to a resx file.
But, when I open my Excel file, spaces before and after my data has been added like this : Excel cell example. And when I convert it to resx file, it does
Resx file example
Here is my resx => excel code :
//I use a application WindowsForm so any 'LBL' / 'TXT make reference to label or textBox I use them to set file or folder path
private void writeExcel()
{
Dictionary<string, string> dataSave = new Dictionary<string, string>();
var path = LBL_DocumentPath.Text;
XDocument doc = XDocument.Load(path);
IEnumerable<XNode> nodes = doc.Descendants("data");
foreach (XElement node in nodes)
{
string name = node.Attribute("name").Value;
string value = node.Value;
dataSave.Add(name, value);
}
CreateExcel(dataSave);
}
private void CreateExcel(Dictionary<string, string> dico)
{
int i = 1;
FileInfo newFile = new FileInfo(LBL_FolderPath.Text + "/" + TXT_FileName.Text + ".xlsx");
using (ExcelPackage package = new ExcelPackage(newFile))
{
try
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventry");
worksheet.Cells[1, 1].Value = "Name";
worksheet.Cells[1, 2].Value = "value";
worksheet.Cells[1, 3].Value = "translation";
foreach (KeyValuePair<string, string> data in dico)
{
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
i++;
worksheet.Cells[i, 1].Value = String.Format("{0}", data.Key);
worksheet.Cells[i, 2].Value = String.Format("{0}", testMessage);
worksheet.Cells.AutoFitColumns();
}
package.Save();
MessageBox.Show("File created ! " + LBL_FolderPath.Text + "\\" + TXT_FileName.Text);
}
catch (Exception)
{
MessageBox.Show("File already exist, checks : " + LBL_DocumentPath.Text + "\\" + TXT_FileName.Text);
}
}
}
If you want all my code, I can give you a dropbox link.
Thanks in advance for any help you can give me.
Math.
Ps: My apologies, my English is not very good. I hope you will understand me correctly
Ok a friend give me solution.
It's my regex which does not work so I replace
string testMessage = String.Format("{0}", data.Value);
string delSpace = testMessage;
Regex regex = new Regex(#"(\s){2,}");
testMessage = regex.Replace(delSpace, "&");
by
string testMessage = String.Format("{0}", data.Value);
testMessage = testMessage.Replace("\n",string.Empty);
testMessage = testMessage.Replace("\r", string.Empty);
testMessage = testMessage.Replace(" ", string.Empty);

Error in exporting fastreport to pdf on asp.net c#

I want to export .frx report that designed by FastReport as an pdf or excel file on a c# web form application like code below:
public static bool ShowReport(string ReportFileName, DataTable ReportData, string DBObjectName, string ExportType, out string Message, params string[] AdditionalParams)
{
FastReport.Utils.Config.WebMode = true;
string ReportFile = HttpContext.Current.Server.MapPath(WPResources.ReportsRoot) + string.Format("{0}_{1}.frx", ReportFileName, ExportType.ToUpper());
FastReport.Report objReport = new FastReport.Report();
objReport.Load(ReportFile);
objReport.Dictionary.Connections.Clear();
System.Data.DataTable resultTable = new DataTable();
objReport.RegisterData(ReportData, DBObjectName);
objReport.GetDataSource(DBObjectName).Enabled = true;
int ParamsCount = AdditionalParams.Length;
if ((ParamsCount % 2) != 0)
ParamsCount--;
for (int i = 0; i < ParamsCount; i += 2)
{
var DynamicControl = (objReport.FindObject(AdditionalParams[i]) as FastReport.TextObject);
if (DynamicControl != null)
{
DynamicControl.Text = AdditionalParams[i + 1];
DynamicControl.Visible = !string.IsNullOrEmpty(AdditionalParams[i + 1]);
}
}
(objReport.FindObject("rptData") as FastReport.DataBand).DataSource = objReport.GetDataSource(DBObjectName);
string fileName = Path.GetFileNameWithoutExtension(ReportFile);
fileName += "_" + WPFarsiDate.Today.ToString().Replace("/", ".") + "_" +
DateTime.Now.Hour.ToString() + "." +
DateTime.Now.Minute.ToString();
if (ExportType == "Excel")
{
using (MemoryStream objMemoryStream = new MemoryStream())
{
objReport.Prepare(false);
FastReport.Export.OoXML.Excel2007Export objExcel2007Export = new FastReport.Export.OoXML.Excel2007Export();
objExcel2007Export.OpenAfterExport = false;
objExcel2007Export.Export(objReport, objMemoryStream);
byte[] buffer = objMemoryStream.ToArray();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("inline;filename={0}.xlsx", fileName));
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.End();
}
}
else if (ExportType == "Pdf")
{
using (MemoryStream objMemoryStream = new MemoryStream())
{
objReport.Prepare(false);
FastReport.Export.Pdf.PDFExport objPDFExport = new FastReport.Export.Pdf.PDFExport();
objPDFExport.EmbeddingFonts = true;
objPDFExport.OpenAfterExport = false;
objPDFExport.Export(objReport, objMemoryStream);
byte[] buffer = objMemoryStream.ToArray();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.pdf", fileName));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.End();
}
}
Message = string.Empty;
return true;
}
When I export it to excel, that is no any matter and it will be done successfuly. But when I export it to pdf, I get this error:
Showing a modal dialog box or form when the application is not running
in UserInteractive mode is not a valid operation. Specify the
ServiceNotification or DefaultDesktopOnly style to display a
notification from a service application.
It should be noted that mentioned error just occurs in the main server and the job can be done successfully in localhost.
It would be very helpful if someone could explain solution for this problem.
After much effort, I find solution for the problem. Fonts used in .frx files weren't the windows/fonts folder. So I copied the metioned fonts there and it worked properly.
Did you tried debug it? Which line throws this error?
Did you see any dialog windows in desktop version? Try to avoid it.
I use fast report in one of my ASP.Net Web Forms projects and I see this exception when I try to export PDF. I have this tag in .aspx file:
<fastreport:webreport id="remainedLeave" runat="server"
Width="100%" Height="100%"></fastreport:webreport>
Adding this property to fast report tag solved my problem:
PdfEmbeddingFonts="false"

Export Issue with Datatable to CSV

I have used ext.net 1.6 tool. I tried to convert data datatable to csv but i am getting error status code : 200 and status text : Bad Request.
And I also exported data from ext.net gridpanel to csv but now i want to export directly datatable to csv.
I passed Jason string for datatable same as passed for gridpanel but gridpanel data is exported perfectly, but datatable does not export with same method
can you suggest me?
what is exact problem with that?
Thanks
Use the below
Method to convert the Datatable data to export into CSV in c#:
void ToCSVDownload(DataTable dtDataTable)
{
var stream = new MemoryStream();
StreamWriter sw = new StreamWriter(stream);
//Writing Headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
//Writing Data
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
//converting it to the Bytes
byte[] byteArray = stream.ToArray();
//Dowloading the file by writing Bytes
Response.AddHeader("Content-Disposition", "attachment; Filename = test.csv");
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(byteArray);
Response.End();
}

Categories