CSV export repeats headers with each field value - crystal-reports

I know this is going to be a really simple answer... when I export my header comes out on each export line preceding the fields that are being exported. I want the header line to export in csv in the 1st line, with the record lines underneath.

When you select CSV as your export option it'll open a new dialog box. In it, note the Report and Page Sections section. Leave it set to Export but be sure to check Isolate Report/Page sections. It'll then work how you'd expect.

You can display the crystal reports as CSV files in the same way as they appear in reports by doing the below thing. This will export into pdf excel or word in exactly same way you want to display
string contentType = "";
ExportOptions options = new ExportOptions();
switch (formatType.ToLower())
{
case "pdf":
default:
options.ExportFormatType = ExportFormatType.PortableDocFormat;
contentType = "application/pdf";
break;
case "excel":
options.ExportFormatType = ExportFormatType.Excel;
contentType = "application/vnd.ms-excel";
break;
case "csv":
contentType = "application/csv";
options.ExportFormatType = ExportFormatType.CharacterSeparatedValues;
//CharacterSeparatedValuesFormatOptions v= ExportOptions.CreateCharacterSeparatedValuesFormatOptions();
//v.SeparatorText
options.ExportFormatOptions = new CharacterSeparatedValuesFormatOptions()
{
ExportMode = CsvExportMode.Standard,
GroupSectionsOption= CsvExportSectionsOption.ExportIsolated,
ReportSectionsOption = CsvExportSectionsOption.ExportIsolated
};
break;
}

This discussion suggests a couple options:
Export to Excel first, then save as CSV
Modify some registry keys
http://sagecity.na.sage.com/support_communities/sage100_erp/f/97/p/38336/125272

Related

XLSX file via OpenXml SDK Both Valid and Invalid

I have a program which exports a System.Data.DataTable to an XLSX / OpenXml Spreadsheet. Finally have it mostly working. However when opening the Spreadsheet in Excel, Excel complains about the file being invalid, and needing repair, giving this message...
We found a problem with some content in . Do you want us to
try to recover as much as we can? If you trust the source of the
workbook, clik Yes.
If I click Yes, it comes back with this message...
Clicking the log file and opening that, just shows this...
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<logFileName>error268360_01.xml</logFileName>
<summary>Errors were detected in file 'C:\Users\aabdi\AppData\Local\Temp\data.20190814.152538.xlsx'</summary>
<repairedRecords>
<repairedRecord>Repaired Records: Cell information from /xl/worksheets/sheet1.xml part</repairedRecord>
</repairedRecords>
</recoveryLog>
Obviously, we don't want to deploy this into a production environment like this. So I've been trying to figure out how to fix this. I threw together a quick little sample to validate the XML and show the errors, based on this link from MSDN. But when I run the program and load the exact same XLSX document that Excel complains about, the Validator comes back saying that the file is perfectly Valid. So I'm not sure where else to go from there.
Any better tools for trying to validate my XLSX XML? Following is the complete code I'm using to generate the XLSX file. (Yes, it's in VB.NET, it's a legacy app.)
If I comment out the line in the For Each dr As DataRow loop, then the XLSX file opens fine in Excel, (just without any data). So it's something with the individual cells, but I'm not really DOING much with them. Setting a value and data type, and that's it.
I also tried replacing the For Each loop in ConstructDataRow with the following, but it still outputs the same "bad" XML...
rv.Append(
(From dc In dr.Table.Columns
Select ConstructCell(
NVL(dr(dc.Ordinal), String.Empty),
MapSystemTypeToCellType(dc.DataType)
)
).ToArray()
)
Also tried replacing the call to Append with AppendChild for each cell too, but that didn't help either.
The zipped up XLSX file (erroring, with dummy data) is available here:
https://drive.google.com/open?id=1KVVWEqH7VHMxwbRA-Pn807SXHZ32oJWR
Full DataTable to Excel XLSX Code
#Region " ToExcel "
<Extension>
Public Function ToExcel(ByVal target As DataTable) As Attachment
Dim filename = Path.GetTempFileName()
Using doc As SpreadsheetDocument = SpreadsheetDocument.Create(filename, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook)
Dim data = New SheetData()
Dim wbp = doc.AddWorkbookPart()
wbp.Workbook = New Workbook()
Dim wsp = wbp.AddNewPart(Of WorksheetPart)()
wsp.Worksheet = New Worksheet(data)
Dim sheets = wbp.Workbook.AppendChild(New Sheets())
Dim sheet = New Sheet() With {.Id = wbp.GetIdOfPart(wsp), .SheetId = 1, .Name = "Data"}
sheets.Append(sheet)
data.AppendChild(ConstructHeaderRow(target))
For Each dr As DataRow In target.Rows
data.AppendChild(ConstructDataRow(dr)) '// THIS LINE YIELDS THE BAD PARTS
Next
wbp.Workbook.Save()
End Using
Dim attachmentname As String = Path.Combine(Path.GetDirectoryName(filename), $"data.{Now.ToString("yyyyMMdd.HHmmss")}.xlsx")
File.Move(filename, attachmentname)
Return New Attachment(attachmentname, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
End Function
Private Function ConstructHeaderRow(dt As DataTable) As Row
Dim rv = New Row()
For Each dc As DataColumn In dt.Columns
rv.Append(ConstructCell(dc.ColumnName, CellValues.String))
Next
Return rv
End Function
Private Function ConstructDataRow(dr As DataRow) As Row
Dim rv = New Row()
For Each dc As DataColumn In dr.Table.Columns
rv.Append(ConstructCell(NVL(dr(dc.Ordinal), String.Empty), MapSystemTypeToCellType(dc.DataType)))
Next
Return rv
End Function
Private Function ConstructCell(value As String, datatype As CellValues) As Cell
Return New Cell() With {
.CellValue = New CellValue(value),
.DataType = datatype
}
End Function
Private Function MapSystemTypeToCellType(t As System.Type) As CellValues
Dim rv As CellValues
Select Case True
Case t Is GetType(String)
rv = CellValues.String
Case t Is GetType(Date)
rv = CellValues.Date
Case t Is GetType(Boolean)
rv = CellValues.Boolean
Case IsNumericType(t)
rv = CellValues.Number
Case Else
rv = CellValues.String
End Select
Return rv
End Function
#End Region
For anyone else coming in and finding this, I finally tracked this down to the Cell.DataType
Setting a value of CellValues.Date will cause Excel to want to "fix" the document.
(apparently for dates, the DataType should be NULL, and Date was only used in Office 2010).
Also, if you specify a DataType of CellValues.Boolean, then the CellValue needs to be either 0 or 1. "true" / "false" will also cause Excel to want to "fix" your spreadsheet.
Also, Microsoft has a better validator tool already built for download here:
https://www.microsoft.com/en-us/download/details.aspx?id=30425

How to used a blank delimiter when exporting CSV

I would like to export crystal report into csv but withouter a delimter character around fields,
here is a snipper of my code:
ExportOptions exportOpts = new ExportOptions();
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
exportOpts.ExportFormatType = ExportFormatType.CharacterSeparatedValues;
DiskFileDestinationOptions DiskFileDestinationOpt = ExportOptions.CreateDiskFileDestinationOptions();
DiskFileDestinationOpt.DiskFileName = filename;
exportOpts.ExportDestinationOptions = DiskFileDestinationOpt;
CharacterSeparatedValuesFormatOptions csvOptions = new CharacterSeparatedValuesFormatOptions();
csvOptions.Delimiter = "";
csvOptions.SeparatorText = "";
exportOpts.ExportFormatOptions = csvOptions;
crystalReportDoc.Export(exportOpts);
the problem is whenever I use an empty string for the delimiter property, crystal report will use the default double quote character in the result csv file.
can someone please assist on how to export a csv document with a blank delimiter?
If you use a blank delimiter, it's not a csv file. (Comma-separated value) You're probably looking for more of a "Text" file type.

Copy range with conditional formatting

I have a range with Conditional Formatting in an existing Excel file. I used EPPlus to copy that range to a new sheet, then I found the conditional formatting was missing.
Is there any way to copy range with conditional formatting using EPPlus?
I found a solution for this. I did not test it on all formattingRuleTypes. (Only needed 2 of them for the moment)
In my application i have 1 template row for each sheet.
var formatList = fromSheet.ConditionalFormatting.ToList();
foreach (var cf in formatList)
{
// sourceRow is the row containing the formatting
if (cf.Address.Start.Row == sourceRow )
{
IExcelConditionalFormattingRule rule = null;
switch (cf.Type)
{
case OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType.GreaterThan:
rule = dest.ConditionalFormatting.AddGreaterThan();
break;
case OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType.GreaterThanOrEqual:
rule = dest.ConditionalFormatting.AddGreaterThanOrEqual();
break;
case OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType.LessThan:
rule = dest.ConditionalFormatting.AddLessThan();
break;
case OfficeOpenXml.ConditionalFormatting.eExcelConditionalFormattingRuleType.LessThanOrEqual:
rule = dest.ConditionalFormatting.AddLessThanOrEqual();
break;
default:
break;
}
rule.Style.Fill = cf.Style.Fill;
rule.Style.Border = cf.Style.Border;
rule.Style.Font = cf.Style.Font;
rule.Style.NumberFormat = cf.Style.NumberFormat;
// I have no clue why the Formula property is not included in the IExcelConditionalFormattingRule interface. So I needed to cast this.
((ExcelConditionalFormattingRule)rule).Formula = ((ExcelConditionalFormattingRule)cf).Formula;
((ExcelConditionalFormattingRule)rule).Formula2 = ((ExcelConditionalFormattingRule)cf).Formula2;
// Calculate the new address for the formatting. This will be different in your case
var adr = new ExcelAddress( dest.Start.Row , cf.Address.Start.Column -1 , dest.Start.Row, cf.Address.Start.Column -1 + cf.Address.Columns -1 );
rule.Address = adr;
I have no clue why the Formula property is not included in the IExcelConditionalFormattingRule interface. So I needed to cast this.
To add to the answer of Luc Wuyts (I can't comment yet due to limited reputation):
// I have no clue why the Formula property is not included in the IExcelConditionalFormattingRule interface. So I needed to cast this.
((ExcelConditionalFormattingRule)rule).Formula = ((ExcelConditionalFormattingRule)cf).Formula;
((ExcelConditionalFormattingRule)rule).Formula2 = ((ExcelConditionalFormattingRule)cf).Formula2;
Some conditional formatting do not have the Formula-options. This cast will work, but applying the Formula properties to conditional formatting options which do not require it will have unforeseen results. Eg. the ConditionalFormatting.AddContainsBlanks() does not require Formula properties, and adding them might mess up the conditional formatting. A better approach is to check the type, and add the formula's only when required.
I had a similar problem, the only way I found to inspect, change or delete a conditional format of a cell or range is looking at the openxml specs. The conditional format is stored in the worksheet, with the range under the attribute sqref. So you can edit that range or add a new.
For example:
DIM p As New ExcelPackage(New FileInfo(ExlReportPath), True)
Dim ws As ExcelWorksheet = p.Workbook.Worksheets(ExlSheetName)
'--Find Node "worksheet" (1 in my case) , Find all Child Nodes "conditionalFormatting" (5 to 11 in my test)
Print.Debug(ws.WorksheetXml.ChildNodes(1).ChildNodes(5).Name)
'--You get: conditionalFormatting
'--Now you can inspect the range:
Print.Debug(ws.WorksheetXml.ChildNodes(1).ChildNodes(5).Attributes("sqref").Value)
'--Will give you the cell address that this formatting applies to example: "D11:D15"
'--you can change delete or add new range if you want, below I add F11:F15
ws.WorksheetXml.ChildNodes(1).ChildNodes(5).Attributes("sqref").Value="D11:D15 F11:F15"
'--You can inspect the rule itself in the InnerXml also...
If you need more details of the markup, google Wouter van Vugt, "Open XML The markup explained". I found it useful and the full document was online (free).
If you find an easier way please post it.
Regards

Varying pagination in different formats of a report

Using iReport, I am generating reports to be viewed in multiple formats. Is it possible for me to ignore pagination only for particular formats like HTML and let it be true for the rest?
With isIgnorePagination="false" the HTML preview appears in chunks. However, setting it to true makes the PDF output a single page.
Any suggestions?
Why yes you can. Add the the IS_IGNORE_PAGINATION with the appropriate value before you export your report. You can set the value at run time based on what your export format is.
params.put("IS_IGNORE_PAGINATION", true);
I found one solution for this problem:
paramaters.put("fromDate", fromDate);
paramaters.put("toDate", toDate);
if (!output.equals("pdf"))
{
paramaters.put("IS_IGNORE_PAGINATION", true);
}
else
paramaters.put("IS_IGNORE_PAGINATION", false);
JasperPrint jasperPrint = null;
jasperPrint = JasperFillManager.fillReport(CompiledReport, paramaters, connection);
if (output.equals("html")) {
generateHtmlResponse(response, jasperPrint);
} else if (output.equals("pdf")) {
generatePdfResponse(response, jasperPrint);
} else if(output.equals("excel")) {
generateXLResponse(response, jasperPrint);
}

How to limit export formats in crystal reports

For Crystal reports for visual studio .net 2005, you can export the report
to various file format such as pdf, excel, word, rpt etc. If I just want to
limit the user see only excel and word format and set the default file
format to excel, is there a way to do it? Sometimes too many choose is
not good, is it?
Using CRVS2010 , you can remove unwanted export Option.
A new feature of CRVS2010 is the ability to modify the available export formats from the viewer export button. The following C# sample code demonstrates how to set the CrystalReportViewer to export only to PDF and Excel file formats:
int exportFormatFlags = (int)(CrystalDecisions.Shared.ViewerExportFormats.PdfFormat | CrystalDecisions.Shared.ViewerExportFormats.ExcelFormat);
CrystalReportViewer1.AllowedExportFormats = exportFormatFlags;
For More Details Please refer below link..
http://scn.sap.com/community/crystal-reports-for-visual-studio/blog/2011/01/26/export-file-formats-for-sap-crystal-reports-for-vs-2010
Try this:
Dim formats As Integer
formats = (CrystalDecisions.Shared.ViewerExportFormats.PdfFormat Or CrystalDecisions.Shared.ViewerExportFormats.XLSXFormat)
CrystalReportViewer1.AllowedExportFormats = formats
You don't mention whether you are using C# / VB.NET or Web/WinForms.
C#
I don't think this is possible. You would have to implement your own Export Button.
Something along the lines of this MSDN article
C#
// Declare variables and get the export options.
ExportOptions exportOpts = new ExportOptions();
ExcelFormatOptions excelFormatOpts = new ExcelFormatOptions ();
DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
exportOpts = Report.ExportOptions;
// Set the excel format options.
excelFormatOpts.ExcelUseConstantColumnWidth = true;
exportOpts.ExportFormatType = ExportFormatType.Excel;
exportOpts.FormatOptions = excelFormatOpts;
// Set the disk file options and export.
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile;
diskOpts.DiskFileName = fileName;
exportOpts.DestinationOptions = diskOpts;
Report.Export ();
VB.NET
' Declare variables and get the export options.
Dim exportOpts As New ExportOptions()
Dim diskOpts As New DiskFileDestinationOptions()
Dim excelFormatOpts As New ExcelFormatOptions()
exportOpts = Report.ExportOptions
' Set the excel format options.
excelFormatOpts.ExcelTabHasColumnHeadings = true
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.FormatOptions = excelFormatOpts
' Set the export format.
exportOpts.ExportFormatType = ExportFormatType.Excel
exportOpts.ExportDestinationType = ExportDestinationType.DiskFile
' Set the disk file options.
diskOpts.DiskFileName = fileName
exportOpts.DestinationOptions = diskOpts
Report.Export()
VB.NET
You used to be able to remove certain export DLLs from the client installation. i.e remove all apart from the Excel DLLs and then it would only display the export options as Excel
To disable Crystal Report Rpt format try this :
Dim formats As Integer
formats = (CrystalDecisions.Shared.ViewerExportFormats.AllFormats Xor CrystalDecisions.Shared.ViewerExportFormats.RptFormat)
CrystalReportViewer1.AllowedExportFormats = formats
Or Short Version :
CrystalReportViewer1.AllowedExportFormats = (CrystalDecisions.Shared.ViewerExportFormats.AllFormats Xor CrystalDecisions.Shared.ViewerExportFormats.RptFormat)