How to limit export formats in crystal reports - 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)

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.

OpenXML SDK and MathML

I use MathML to create some data blocks and I need to insert it throught OpenXML SDK into docx file. I've heard it is possible, but I didn't manage it. Could somebody help me with this problem?
As far as I know, the OpenXml SDK does not support presentation MathML out of the box.
Instead, the OpenXml SDK supports Office MathML.
So, to insert presentation MathML into a word document we first have
to transform the presentation MathML into Office MathML.
Fortunately, Microsoft provides a XSL file (called MML2OMML.xsl) to transform presentation MathML
into Office MathML. The file MML2OMML.xsl is located under %ProgramFiles%\Microsoft Office\Office12.
In conjunction with the .Net Framework class
XslCompiledTransform we are able to transform presentation MathML into Office MathML.
The next step is to create a OfficeMath object from the transformed MathML.
The OfficeMath class represents a run containing WordprocessingML which shall be handled as though it was Office Open XML Math.
For more info please refer to MSDN.
The presentation MathML does not contain font information. To get a nice result
we must add font information to the created OfficeMath object.
In the last step we have to add the OfficeMath object to our word document.
In the example below I simply search for the first Paragraph in a
word document called template.docx and add the OfficeMath object to the found paragraph.
XslCompiledTransform xslTransform = new XslCompiledTransform();
// The MML2OMML.xsl file is located under
// %ProgramFiles%\Microsoft Office\Office12\
xslTransform.Load("MML2OMML.xsl");
// Load the file containing your MathML presentation markup.
using (XmlReader reader = XmlReader.Create(File.Open("mathML.xml", FileMode.Open)))
{
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = xslTransform.OutputSettings.Clone();
// Configure xml writer to omit xml declaration.
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.OmitXmlDeclaration = true;
XmlWriter xw = XmlWriter.Create(ms, settings);
// Transform our MathML to OfficeMathML
xslTransform.Transform(reader, xw);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms, Encoding.UTF8);
string officeML = sr.ReadToEnd();
Console.Out.WriteLine(officeML);
// Create a OfficeMath instance from the
// OfficeMathML xml.
DocumentFormat.OpenXml.Math.OfficeMath om =
new DocumentFormat.OpenXml.Math.OfficeMath(officeML);
// Add the OfficeMath instance to our
// word template.
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open("template.docx", true))
{
DocumentFormat.OpenXml.Wordprocessing.Paragraph par =
wordDoc.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault();
foreach (var currentRun in om.Descendants<DocumentFormat.OpenXml.Math.Run>())
{
// Add font information to every run.
DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 =
new DocumentFormat.OpenXml.Wordprocessing.RunProperties();
RunFonts runFonts2 = new RunFonts() { Ascii = "Cambria Math", HighAnsi = "Cambria Math" };
runProperties2.Append(runFonts2);
currentRun.InsertAt(runProperties2, 0);
}
par.Append(om);
}
}
}

CSV export repeats headers with each field value

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

Custom clipboard data format accross RDC (.NET)

I'm trying to copy a custom object from a RDC window into host (my local) machine. It fails.
Here's the code that i'm using to 1) copy and 2) paste:
1) Remote (client running on Windows XP accessed via RDC):
//copy entry
IDataObject ido = new DataObject();
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
StringWriter sw = new StringWriter();
x.Serialize(sw, new EntryForClipboard(entry));
ido.SetData(typeof(EntryForClipboard).FullName, sw.ToString());
Clipboard.SetDataObject(ido, true);
2) Local (client running on local Windows XP x64 workstation):
//paste entry
IDataObject ido = Clipboard.GetDataObject();
DataFormats.Format cdf = DataFormats.GetFormat(typeof(EntryForClipboard).FullName);
if (ido.GetDataPresent(cdf.Name)) //<- this always returns false
{
//can never get here!
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
string xml = (string)ido.GetData(cdf.Name);
StringReader sr = new StringReader(xml);
EntryForClipboard data = (EntryForClipboard)x.Deserialize(sr);
}
It works perfectly on the same machine though.
Any hints?
There are a couple of things you could look into:
Are you sure the serialization of the object truely converts it into XML? Perhaps the outputted XML have references to your memory space? Try looking at the text of the XML to see.
If you really have a serialized XML version of the object, why not store the value as plain-vanilla text and not using typeof(EntryForClipboard) ? Something like:
XmlSerializer x = new XmlSerializer(typeof(EntryForClipboard));
StringWriter sw = new StringWriter();
x.Serialize(sw, new EntryForClipboard(entry));
Clipboard.SetText(sw.ToString(), TextDataFormat.UnicodeText);
And then, all you'd have to do in the client-program is check if the text in the clipboard can be de-serialized back into your object.
Ok, found what the issue was.
Custom format names get truncated to 16 characters when copying over RDC using custom format.
In the line
ido.SetData(typeof(EntryForClipboard).FullName, sw.ToString());
the format name was quite long.
When i was receiving the copied data on the host machine the formats available had my custom format, but truncated to 16 characters.
IDataObject ido = Clipboard.GetDataObject();
ido.GetFormats(); //used to see available formats.
So i just used a shorter format name:
//to copy
ido.SetData("MyFormat", sw.ToString());
...
//to paste
DataFormats.Format cdf = DataFormats.GetFormat("MyFormat");
if (ido.GetDataPresent(cdf.Name)) {
//this not works
...