Editing gridview excel export - c#

I currently implemented a method such that it'll export to excel any RadGridView passed as a parameter. It exports completely fine, I want to enhance it by adding a Title to the first row of the excel file then append the RadGridView underneath that row. May I ask if anyone has an idea how abouts I should do that?
public static void Export(RadGridView grid)
{
const string extension = "xls";
var dialog = new SaveFileDialog
{
DefaultExt = extension,
Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
FilterIndex = 1
};
if (dialog.ShowDialog() != true)
{
return;
}
using (var stream = dialog.OpenFile())
{
var exportOptions = new GridViewExportOptions
{
Format = ExportFormat.ExcelML,
ShowColumnHeaders = true,
ShowColumnFooters = true,
ShowGroupFooters = false,
};
exportOptions.Items = (IEnumerable)grid.ItemsSource;
grid.Export(stream, exportOptions);
}
}

If it interest anyone. Here's the solution I used,
public static void ExportWithHeader(RadGridView grid, string header)
{
try
{
string extension = "xls";
SaveFileDialog dialog = new SaveFileDialog()
{
DefaultExt = extension,
Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
FilterIndex = 1,
FileName = header
};
if (dialog.ShowDialog() == true)
{
using (Stream stream = dialog.OpenFile())
{
MemoryStream ms = new MemoryStream();
grid.Export(
ms,
new GridViewExportOptions()
{
Format = ExportFormat.ExcelML,
ShowColumnHeaders = true,
ShowColumnFooters = true,
ShowGroupFooters = false,
});
ms.Seek(0, SeekOrigin.Begin);
header = String.Format(
"<Row><Cell ss:Index='1'><Data ss:Type='String'>{0}</Data></Cell></Row>", header);
StreamReader sr = new StreamReader(ms);
string msStr = sr.ReadToEnd();
msStr = msStr.Insert(msStr.IndexOf("<Row>"), header);
stream.Write(Encoding.UTF8.GetBytes(msStr), 0, msStr.Length);
}
Process.Start(dialog.FileName);
}
}
catch
{
Notification.Error("Process Busy", "Please exit excel instance.");
}
}

Related

Trying to export telerik winform grouped grid data to excel?

When i export grid data without grouping it exports perfectly but when i export grid data with grouping it skips rows and if i remove header rows then data is exported perfectly with or without grouping?
I think the problem is in header rows when i remove header rows then it works perfectly.
Please tell me how can i adjust header rows so that grouped data can be exported perfectly
private void btnExport_Click(object sender, EventArgs e)
{
saveFileDialog1.FileName = this.ReportHeaderText.Replace(' ', '-').Replace('/', '-');
saveFileDialog1.OverwritePrompt = true;
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
{
return;
}
if (saveFileDialog1.CheckFileExists)
{
}
if (saveFileDialog1.FileName.Equals(String.Empty))
{
RiceMsgBox.ShowErrorBox("Please enter a file name.");
return;
}
string fileName = this.saveFileDialog1.FileName;
bool openExportFile = false;
RunExportToExcelML(fileName, ref openExportFile);
if (openExportFile)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch (Exception ex)
{
RiceMsgBox.ShowErrorBox("The file cannot be opened on your system");
}
}
this.tabControl1.SelectedIndex = 1;
}
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0,30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
// exportRenderer.ExcelTableCreated += exporter_ExcelTableCreated;
//exporter.CellFormatting += exporter_ExcelCellFormatting;
//FormatGridColumns(gridReport);
try
{
exporter.RunExport(fileName, exportRenderer);
var dialog = RiceMsgBox.GetQuestionBox("The data in the grid was exported successfully. Do you want to open the file?");
if (dialog == DialogResult.Yes)
{
openExportFile = true;
}
else
{
openExportFile = false;
}
}
catch(Exception ex)
{
RiceMsgBox.ShowErrorBox("Error exporting data.");
}
}
void exporter_CellFormatting(object sender, Telerik.WinControls.Export.CellFormattingEventArgs e)
{
CellBorders borders = new CellBorders();
borders.Top = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Bottom = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Right = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
borders.Left = new CellBorder(CellBorderStyle.Thin, new ThemableColor(System.Windows.Media.Colors.Black));
e.CellStyleInfo.Borders = borders;
}
void renderer_WorkbookCreated(object sender, Telerik.WinControls.Export.WorkbookCreatedEventArgs e)
{
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = e.Workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
}
The GridViewSpreadExport generates a document that consists of merged cells. Inserting a row on the top and then exporting the document causes wrong merged cells. It is a known issue: link
As a workaround, instead of using the WorkbookCreated event to insert a new row you can export the document and then reopen it and insert a row above the exported grid data.
private void RunExportToExcelML(string fileName, ref bool openExportFile)
{
Telerik.WinControls.Export.GridViewSpreadExport exporter = new Telerik.WinControls.Export.GridViewSpreadExport(gridReport, 0);
exporter.HiddenColumnOption = Telerik.WinControls.UI.Export.HiddenOption.DoNotExport;
exporter.CellFormatting += exporter_CellFormatting;
exporter.ExportVisualSettings = true;
exporter.SheetMaxRows = ExcelMaxRows._1048576;
exporter.SheetName = System.Text.RegularExpressions.Regex.Replace(this.ReportHeaderText.Length > 30 ? this.ReportHeaderText.Substring(0, 30) : this.ReportHeaderText, #"[^0-9a-zA-Z]+", ",");
exporter.SummariesExportOption = SummariesOption.ExportAll;
Telerik.WinControls.Export.SpreadExportRenderer exportRenderer = new Telerik.WinControls.Export.SpreadExportRenderer();
//exportRenderer.WorkbookCreated += renderer_WorkbookCreated;
try
{
exporter.RunExport(fileName, exportRenderer);
this.InsertHeader(fileName);
// more code...
}
private void InsertHeader(string fileName)
{
XlsxFormatProvider formatProvider = new XlsxFormatProvider();
Workbook workbook = null;
using (Stream stream = new FileStream(fileName, FileMode.Open))
{
workbook = formatProvider.Import(stream);
}
PatternFill solidPatternFill = new PatternFill(PatternType.Solid, System.Windows.Media.Colors.Transparent, System.Windows.Media.Colors.Transparent);
CellValueFormat textFormat = new CellValueFormat("#");
//string dateRange = "( From Date : " + dtpFromDate.Text + " - To Date : " + dtpToDate.Text + " )";
Worksheet worksheet = workbook.Sheets[0] as Worksheet;
worksheet.Columns[worksheet.UsedCellRange].AutoFitWidth();
CellRange range = new CellRange(0, 0, 1, gridReport.Columns.Count);
CellSelection header = worksheet.Cells[range];
if (header.CanInsertOrRemove(range, ShiftType.Down))
{
header.Insert(InsertShiftType.Down);
}
header.Merge();
header.SetFormat(textFormat);
header.SetHorizontalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadHorizontalAlignment.Center);
header.SetVerticalAlignment(Telerik.Windows.Documents.Spreadsheet.Model.RadVerticalAlignment.Center);
header.SetFontFamily(new ThemableFontFamily("Rockwell"));
header.SetFontSize(24);
header.SetFill(solidPatternFill);
header.SetValue(this.ReportHeaderText);
using (Stream output = new FileStream(fileName, FileMode.Create))
{
formatProvider.Export(workbook, output);
}
}
For more information about SpreadProcessing visit the following link: https://docs.telerik.com/devtools/document-processing/libraries/radspreadprocessing/overview

Perform OCR via MODI on specific region instead of entire document

I am trying to get to perform bulk OCR on images in a selected directory via MODI. Here's the code.
private void button1_Click(object sender, EventArgs e) {
CommonOpenFileDialog dialog = new CommonOpenFileDialog {
InitialDirectory = "C:\\Users",
IsFolderPicker = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok) {
invoicePath = dialog.FileName;
CheckFileAndDoOCR(imageDirectory);
}
}
public string CheckFileAndDoOCR(string directoryPath) {
string TheTxt = "";
IEnumerator files = Directory.GetFiles(directoryPath).GetEnumerator();
while (files.MoveNext()) {
FileInfo foo = new FileInfo(Convert.ToString(files.Current));
if (foo.Extension == ".jpg" || foo.Extension == ".JPG") {
TheTxt = DoOCR(foo.FullName);
string txtFileName = foo.DirectoryName + "\\" + foo.Name.Replace(foo.Extension, "") + ".txt";
FileStream createFile = new FileStream(txtFileName, FileMode.OpenOrCreate);
StreamWriter writeFile = new StreamWriter(createFile);
writeFile.Write(TheTxt);
writeFile.Close();
createFile.Close();
}
try {
foo.Delete();
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return TheTxt;
}
public string DoOCR(string FullPath) {
MODI.Document miDoc;
MODI.Word miWord;
MODI.IMiRects miRects;
MODI.IMiRect miRect;
string strRectInfo;
miRect = null;
string txt;
string word;
MODI.Document md = new MODI.Document();
md.Create(FullPath);
md.OCR(MODI.MiLANGUAGES.miLANG_ENGLISH, false, false);
MODI.Image image = (MODI.Image)md.Images[0];
txt = image.Layout.Text;
word = null;
image = null;
md.Close(false);
md = null;
GC.Collect();
GC.WaitForPendingFinalizers();
return txt;
}
How can I perform the OCR on a specific area, for example
Rectangle Area = new Rectangle() {
X = 1367,
Y = 420,
Height = 57,
Width = 411
};
I have to extract data from one region/rectangle only from all the images. How can I do that? I have tried IronOCR and Tesseract, works like a charm. But I have been told to use MODI. Please help.

could not find part of path

i'm trying to convert a DataTable to an excel-file but at the time of creation of file it gives me error: could not find part of path.
string strDirectorypath = HttpContext.Current.Server.MapPath("~/ExcelUpload/");
DateTime dtbatchtime = Convert.ToDateTime(strBatchProcesstime);
strBatchProcesstime = dtbatchtime.ToString("MM-dd-yyyy_hh_mm_ss");
string strFilename = "FailedExcel_" + strBatchProcesstime + ".csv";
string csvdownloadPath = Path.Combine(strDirectorypath, strFilename);
using (FileStream File_Stream = new FileStream(csvdownloadPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter FileWriter = new StreamWriter(File_Stream))
{
FileWriter.BaseStream.Seek(0, SeekOrigin.End);
string[] columns = { "Opportunity Name", "Property Id", "Error Type", "Error Message", "Time" };//set columns here as in the Excel Sheet.
CreateColumns(FileWriter, columns);
FileWriter.WriteLine();
if (dtRecords.Rows.Count > 0)
{
for (int i = 0; i < dtRecords.Rows.Count; i++)
{
string[] values = {
dtRecords.Rows[i]["OpportunityName"].ToString(),
dtRecords.Rows[i]["PropertyId"].ToString(),
dtRecords.Rows[i]["ErrorType"].ToString(),
dtRecords.Rows[i]["ErrorMessage"].ToString(),
dtRecords.Rows[i]["TimeStamp"].ToString()
};
CreateColumns(FileWriter, values);
FileWriter.WriteLine();
}
}
}
}
If the directory does not exist, it won't be created, so you should check and create:
if (!Directory.Exists(strDirectorypath)) {
Directory.Create(strDirectorypath);
}
Expand that with degrees of checks for your own reliability/sanity.

Dynamically Insert Image to PDF using LiveCycle/ITextSharp

I have a pdf template I created using LiveCycle Designer. Inside it, I have 3 Image Fields that I created, ImageField1, ImageField2, ImageField3. The images are located on a url, let's call it "http://images.com/img/IMAGENAME.jpg", and the user selects the images prior to generating the pdf in which case I store the image names in a string array.
Is it possible to add these images programmatically into the Image Fields? The methods I've tried so far have only lead to a corrupted pdf that won't open at all.
public string Foo(int id)
{
try
{
var file = string.Empty;
var property = ((IRepositoryBase)PropertyRepository).GetById<Property>(id);
var purchase = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyPurchase>(id);
var inspection = ((IRepositoryBase)PropertyRepository).GetByPropertyId<PropertyInspection>(id);
file = HttpContext.Current.Server.MapPath("\\Assets\\documents\\originals\\Brochure.pdf");
var tmp = HttpContext.Current.Server.MapPath("\\Assets\\documents\\temps\\");
tmp += string.Format("{0}-Brochure.pdf", property.Id);
var pdfReader = new PdfReader(file);
var pdfStamper = new PdfStamper(pdfReader, new FileStream(tmp, FileMode.Create));
var pdfFormFields = pdfStamper.AcroFields;
var pht = property.BrochurePhoto;
string[] photos = pht.Split(' ');
PdfContentByte cB = new PdfContentByte(pdfStamper.Writer);
if (photos[0] != null)
{
iTextSharp.text.Image photoToPdf1 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[0].ToString() + ".jpg"));
cB.AddImage(photoToPdf1);
}
if (photos[1] != null)
{
iTextSharp.text.Image photoToPdf2 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[1].ToString() + ".jpg"));
cB.AddImage(photoToPdf2);
}
if (photos[2] != null)
{
iTextSharp.text.Image photoToPdf3 = iTextSharp.text.Image.GetInstance(new Uri("http://images.com/img/" + photos[2].ToString() + ".jpg"));
cB.AddImage(photoToPdf3);
}
pdfStamper.FormFlattening = false;
pdfStamper.Close();
return string.Format("{0}-Brochure.pdf", property.Id);
}
catch (Exception ex)
{
Log.Error(ex);
return string.Empty;
}
}

How can I save the values from fields in a Windows Forms GUI to a file, and then restore them?

I want to load content stored in a file, into the fields of a WinForms GUI.
My approach right now: I've got a streamwriter which writes each text box to a line in a .txt file. I have the streamreader setup but i have no idea how to get it to load each line into seperate text boxes. For example: Task1_name (line 1) and task1_desc (line 2) need to be in seperate text boxes, how could i get it to load into the boxes?
Thanks
Code:
Save Button:
void Save_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save?", "Save", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.WriteLine(task1_name.Text);
sw.WriteLine(task1_desc.Text);
sw.WriteLine(task1_date.Value);
sw.WriteLine(task1_check.Checked);
sw.Close();
}
}
Load Button:
void Load_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to load?", "Load", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamReader sr = new StreamReader(file);
sr.Close();
}
}
Use XML Serialization. It would look something like this:
public class MySettings
{
public String name {get;set;}
public String name {get;set;}
public DateTime date {get;set;}
public bool checked {get;set;}
}
void Save()
{
var s = new MySettings
{
name = this.task1_Name.Text,
desc = this.task1_Desc.Text,
date = this.task1_Date.Value,
checked = this.task1_Check.Checked
};
var ser = new XmlSerializer(typeof(MySettings));
using (var fs = new FileStream(path, FileMode.Create))
{
using (var tw = new StreamWriter(fs, new UTF8Encoding()))
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ser.Serialize(tw, this, ns);
}
}
}
And to load it would look like this:
static MySettings Load()
{
var ser = new XmlSerializer(typeof(MySettings));
MySettings settings = null;
try
{
using (var s = File.OpenRead(path))
{
settings = (MySettings) ser.Deserialize(s);
// optionally validate here
}
}
catch (Exception ex1)
{
MessageBox.Show("Cannot read settings. " + ex1.Message,
"error");
settings = null;
}
return settings;
}
And then of course resetting your form would be like this:
var settings = Load();
this.task1_Name.Text = settings.name;
this.task1_Desc.Text = settings.desc;
this.task1_Date.Value = settings.date;
this.task1_Check.Checked = settings.checked;
You can add every line into a List and access them by index:
//...
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(file))
{
while(!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
}
task1_name.Text = lines[0];
task1_desc.Text = lines[1];
//...
Just read the lines and populate the form in the same order as you wrote them:
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamReader sr = new StreamReader(file);
task1_name.Text = sr.ReadLine();
task1_desc.Text = sr.ReadLine();
task1_date.Value = DateTime.Parse(sr.ReadLine());
task1_checked.Checked = bool.Parse(sr.ReadLine());
sr.Close();
}

Categories

Resources