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
Related
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.
I am trying to export an excel and make it password protected.
My code is given below.
But i am getting error:
Excel completed file level validation and repair.
Some parts of this workbook may have been repaired or discarded.
I DON'T KNOW WHAT I AM DOING WRONG .
In-case i do it without the save As line for package then this error doesn't appear.
In my controller:
[HttpGet]
public FileStreamResult ExportToExcel()
{
_objService = new ServiceBAL();
List<ReconcilationEntity> Objmodel = new List<ReconcilationEntity>();
Objmodel = _objService.GetCreditsudharLeads();
String URL = string.Empty;
if (!Directory.Exists(Server.MapPath("~/TempExcel")))
{
System.IO.Directory.CreateDirectory(Server.MapPath("~/TempExcel"));
}
String Filepath = Server.MapPath("~/TempExcel");
string date = DateTime.Now.ToShortDateString().Replace("/", "_") + "_" + DateTime.Now.ToShortTimeString().Replace(" ", "_").Replace(":", "_").Trim();
String FileName = "Creditsudhar_" + date + ".xlsx";
Filepath = Filepath + "\\" + FileName;
string[] columns = { "AffName", "AffPhone", "AffEmail", "ProductName", "ContactName", "Status", "CreatedOn", "Commission", "IsCommissionPaid", "Accountname", "AccountNumber", "BankName", "BankBranch", "IFSCCode", "PanNumber" };
var file = ExcelExportHelper.ExportExcel(ExcelExportHelper.ListToDataTable(Objmodel), Filepath, "Creditsudhar Reconcillation Sheet " + DateTime.Now.ToShortDateString(), true, columns);
var memStream = new MemoryStream(file);
return this.File(memStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName);
}
public static string ExcelContentType
{
get
{ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
}
public static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static byte[] ExportExcel(DataTable dataTable, String Filepath, string heading = "", bool showSrNo = false, params string[] columnsToTake)
{
string fullPath = string.Empty;
byte[] ret;
DeleteUploadedFile(Filepath);
String result = String.Empty;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
// add the content into the Excel file
workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
// autofit width of cells with small content
int columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
try
{
ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
int maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
if (maxLength < 150)
{
workSheet.Column(columnIndex).AutoFit();
}
columnIndex++;
}
catch (Exception ex)
{
if (!(ex is System.Threading.ThreadAbortException))
{
//Log other errors here
}
}
}
// format header - bold, yellow on black
using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
{
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#1fb5ad"));
}
// format cells - add borders
using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
// removed ignored columns
for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
{
if (i == 0 && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + 1);
}
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 5;
}
System.IO.FileInfo fileinfo2 = new System.IO.FileInfo(Filepath);
DeleteUploadedFile(Filepath);
workSheet.Protection.SetPassword("myPassword");
workSheet.Protection.IsProtected = true;
workSheet.Protection.AllowSelectUnlockedCells = false;
workSheet.Protection.AllowSelectLockedCells = false;
package.SaveAs(fileinfo2, "myPassword");
ret = package.GetAsByteArray();
return ret;
}
}
public static void DeleteUploadedFile(String filePath)
{
try
{
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
catch (Exception ex)
{ }
}
public static byte[] ExportExcel<T>(List<T> data, String Filepath, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
{
return ExportExcel(ListToDataTable<T>(data), Filepath, Heading, showSlno, ColumnsToTake);
}
An answer mentioned SaveAs close the package, so the correct steps will be returning the saved file as array instead of using GetAsByteArray afterwards. Or simply use GetAsByteArray(passwords) without SaveAs.
Good Afternoon everyone. I have a question involving taking data in a tablelayoutpanel and placing it into a .pdf using iTextSharp (Unless someone knows a better technology). The tableLayout panel consists of 1 column with 1 row by default and has rows dynamically added given what the data returns.
Here is what I have for printing:
private void btnPrint_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "Save file as...";
dialog.Filter = "Pdf File |*.pdf";
if (dialog.ShowDialog() == DialogResult.OK)
{
Document doc = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(dialog.FileName, FileMode.Create));
doc.Open();
Paragraph entry1 = new Paragraph("Hello World!");
//Page 1 Printing
PdfPTable LegendsForTable = new PdfPTable(this.tblPnlLayLFT.ColumnCount);
doc.Add(entry1);
doc.Close();
MessageBox.Show("File saved");
}
}
catch (Exception exception)
{
MessageBox.Show(#"ERROR: Issue encountered while trying to print. " + Environment.NewLine
+ #"Contact ITSupport with the following the following error" + Environment.NewLine
+ exception);
}
}
Does anyone know a method to copy tablelayoutpanel to .pdf?
I was able to figure this out myself.
Step 1 was to create a loop that iterates through the table layout panels and place the order that I want into a list.
int reIterator = 1;
int replicateIterator = 1;
List<string> table1List = new List<string>();
for (int counter = 0; counter < 6; counter++)
{
while (reIterator < 7)
{
string currentLabel = "LblRE" + reIterator + "R" + replicateIterator;
Label reLabel = this.Controls.Find(currentLabel, true).FirstOrDefault() as Label;
if (reLabel.Text != null)
{
table1List.Add(reLabel.Text);
reIterator = reIterator + 1;
}
else
{
table1List.Add(reLabel.Text = "");
reIterator = reIterator + 1;
}
}
//Builds next row
if (reIterator == 7)
{
replicateIterator = replicateIterator + 1;
reIterator = 1;
}
}
Then using iTextSharp I am able to loop through using the list and add the data to a PDF.
I have a WPF App that allows the user to choose one to many spreadsheets and performs a process to clean the data and write out a pipe delimited files. I am trying to use a Background Worker in order to display a progress bar. The problem I am having is that I have the backgroundworker_DoWork routine to perform the read the excel file, clean the data and write out the data. For each spreadsheet the user is allowed to specify the range for the data or to let Excel decided the range. I call a dialog for this input. I get the error "The calling thread must be STA, because many UI components require this." I have been trying to find a fix for this but everything I try doesn't work.
Here is my code. I have put comments where the offending code is and what I have tried so far.
private void ProcessFiles()
{
int intNumFiles = 0;
string strFileType = "";
int intPos = 0;
string strMsg = "";
intNumFiles = strExFileNames.Length;
foreach (string strInputFile in strExFileNames)
{
intPos = strInputFile.LastIndexOf(".");
strFileType = strInputFile.Substring(intPos + 1);
if(!blnEXTextFileFound)
{
strExcelInputFile = strInputFile;
if (blnExParamCancel || blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
break;
}
prgExcelProgress.Visibility = Visibility.Visible;
txtExcelPercent.Visibility = Visibility.Visible;
EnterExcelStateRunning();
try
{
bgwExcelRunner.RunWorkerAsync(strInputFile);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Trying to run the Excel/Text file clean process resulted in this error: " + ex.Message, " Error");
prgExcelProgress.Foreground = new SolidColorBrush(Colors.DarkRed);
prgExcelProgress.Value = 100;
}
//ReadWriteExcelData(strInputFile);
}
else
{
if (blnEXTextFileFound)
{
ProcessDelimitedFile(strInputFile);
}
else
{
strMsg = "File type " + strFileType + " is not supported.";
strMsg += " Please contact support.";
System.Windows.MessageBox.Show(strMsg);
}
}
}
prgExcelProgress.Value = 100;
//prgIndicator.Width = 400;
//lblPrctPrgrs.Content = "100%";
//grdProgressIndicator.InvalidateVisual();
//System.Windows.Forms.Application.DoEvents();
//Thread.Sleep(2000);
//txtIndicator.Text = "All files have been processed and created in " + strExOutputPath + ".";
blnDoForAll = false;
}
private void bgwExcelRunner_DoWork(object sender, DoWorkEventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range, colrange, rowrange;
string strCellData, strMsg;
string strDataRow = "";
long lngNumRows, lngNumCols = 0;
long intModNumber, lngProgressPct = 0;
double dblProgress = 0;
double dblProgressPct = 0;
string strOutputFileName = "";
int intPos, intProgress = 0;
string strSubFileName = "";
string strFullOutputFileName = "";
string strOutName = "";
long lngColCnt;
string[] strWSNames = new string[0];
Type typCellType;
bool blnMultiWS = false;
string strNumberFormat;
string strFileName = (string)e.Argument;
//string strFileName = (string)((object[])e.Argument)[0];
intPos = strFileName.IndexOf(".");
strSubFileName = strFileName.Substring(0, intPos);
strOutputFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
strOutName = strOutputFileName.Substring(0, strOutputFileName.IndexOf("."));
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(strFileName, 0, true, 5, "", "", true,
Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Sheets excelSheets = xlWorkBook.Worksheets;
if (excelSheets.Count > 1)
{
blnMultiWS = CheckMultipleWorksheets(excelSheets);
if (!blnMultiWS)
{
Array.Clear(strChoosenNames, 0, strChoosenNames.Length);
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
}
else
{
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
if (blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
goto ReadWriteExcelDataExit;
}
foreach (string strCurrWSName in strChoosenNames)
{
//grdProgressIndicator.Visibility = Visibility.Visible;
//txtIndicator.Text = "File: " + strCurrWSName;
//prgIndicator.Width = 0;
//lblPrctPrgrs.Content = "0%";
//System.Windows.Forms.Application.DoEvents();
//txtIndicator.Text = " Processing File: " + strCurrWSName + ". Please wait...";
strFullOutputFileName = strExOutputPath + "\\" + strCurrWSName + "_duc.txt";
//if (strChoosenNames.Length > 1)
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
//}
//else
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//}
try
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
}
catch (Exception exQuery)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
if (!blnDoForAll)
{
// I ALSO TRIED TO USE A THREAD. THIS SEEMS TO WORK EXCEPT THAT IT PROCESSING DOESN'T RUN IN THE FOREGROUND SO IT FALLS TO THE CODE AFTER BEFORE THE DIALOG IS DISPLAYED
//Thread thread = new Thread(() =>
//{
// ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
// ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
// ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// strExcelStartCol = ercWin.strStartCol;
// strExcelEndCol = ercWin.strEndCol;
// lngExcelStartRow = ercWin.lngStartRow;
// lngExcelEndRow = ercWin.lngEndRow;
// blnLetExcelDecide = ercWin.blnExcelDecide;
// blnDoForAll = ercWin.blnDoForAll;
//});
//thread.SetApartmentState(ApartmentState.STA);
//thread.IsBackground = false;
//thread.Start();
// THIS IS ONE ATTEMPT TO USE A DISPATCHER, STILL GET THE STA ERROR
//ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
//ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
//ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
//ercWin.Dispatcher.BeginInvoke
// (
// System.Windows.Threading.DispatcherPriority.Normal,
// (Action)(() =>
// {
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// }
// )
// );
// THIS IS WHERE THE ERROR OCCURS
ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
ercWin.ShowDialog();
blnExParamCancel = ercWin.blnExCancel;
if (blnExParamCancel)
{
prgExcelProgress.Foreground = new SolidColorBrush(Colors.LightPink);
Dispatcher.BeginInvoke((Action)delegate
{
prgExcelProgress.Value = 100;
txtExcelPercent.Text = "Process has been cancelled";
});
blnExParamCancel = false;
goto ReadWriteExcelDataExit;
}
strExcelStartCol = ercWin.strStartCol;
strExcelEndCol = ercWin.strEndCol;
lngExcelStartRow = ercWin.lngStartRow;
lngExcelEndRow = ercWin.lngEndRow;
blnLetExcelDecide = ercWin.blnExcelDecide;
blnDoForAll = ercWin.blnDoForAll;
if (blnLetExcelDecide)
{
range = xlWorkSheet.UsedRange;
}
else
{
Excel.Range c1 = xlWorkSheet.Cells[lngExcelStartRow, strExcelStartCol];
Excel.Range c2 = xlWorkSheet.Cells[lngExcelEndRow, strExcelEndCol];
range = (Excel.Range)xlWorkSheet.get_Range(c1, c2);
}
colrange = range.Columns;
lngNumCols = colrange.Count;
rowrange = range.Rows;
lngNumRows = rowrange.Count;
if (lngNumRows < 10)
{
intModNumber = lngNumRows;
}
else
{
intModNumber = lngNumRows / 10;
}
if (System.IO.File.Exists(#strFullOutputFileName))
{
System.IO.File.Delete(#strFullOutputFileName);
}
object[,] values = (object[,])range.Value;
long NumRow = 1;
using (StreamWriter file = new StreamWriter(#strFullOutputFileName, true, Encoding.GetEncoding("iso-8859-1")))
{
while (NumRow <= values.GetLength(0))
{
strDataRow = "";
for (lngColCnt = 1; lngColCnt <= lngNumCols; lngColCnt++)
{
if (values[NumRow, lngColCnt] == null)
{
typCellType = typeof(System.String);
}
else
{
typCellType = values[NumRow, lngColCnt].GetType();
}
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
if (typCellType == typeof(System.DateTime))
{
strCellData = strCellData.Substring(0, strCellData.IndexOf(" "));
}
else
{
if (typCellType == typeof(System.Decimal))
{
if (Convert.ToDecimal(values[NumRow, lngColCnt]) == 0)
{
strCellData = Convert.ToString(0);
}
else
{
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
}
}
else
{
if (typCellType != typeof(System.String))
{
strNumberFormat = range[NumRow, lngColCnt].NumberFormat.ToString();
if (strNumberFormat != "General" && strNumberFormat != "Text" && strNumberFormat != "#")
{
if (typCellType == typeof(System.Double))
{
if (strNumberFormat.IndexOf("[Red]") > 0)
{
strCellData = Convert.ToString(range[NumRow, lngColCnt].Value2);
}
else
{
double dblCellValue = double.Parse(strCellData);
strCellData = dblCellValue.ToString(strNumberFormat);
}
}
}
}
}
}
if (strCellData == null)
{
strCellData = string.Empty;
}
else
{
strCellData = strCellData.Replace("\r\n", " ").Replace("\n", " ").Replace("\r", " ");
}
if (lngColCnt == lngNumCols)
{
strDataRow += strCellData;
}
else
{
strDataRow += strCellData + "|";
}
}
file.WriteLine(strDataRow);
if (NumRow % intModNumber == 0)
{
lngProgressPct = (NumRow / lngNumRows);
bgwExcelRunner.ReportProgress((int)lngProgressPct);
}
NumRow++;
}
}
releaseObject(xlWorkSheet);
}
xlWorkBook.Close(false, null, null);
ReadWriteExcelDataExit:
blnMWCancel = false;
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Here is the entry point for the ExcelRowColInfo window.
public ExcelRowColInfo(string strWSName)
{
InitializeComponent();
strCurrWSName = string.Copy(strWSName);
InitializeExcelParams();
}
I tried to put [STAThread] above this but get the error "Attributre 'STAThread' is not valid on this declaration type. It is only valid on 'Method' declaration.
How do I do this correctly?
Trying to download excel file from ssrs and using ClosedXML to modified, getting exception.
Following is my code, getting exception at exlWorkBook = new XLWorkbook(FilePath);
public ActionResult ExportToExcel(string VesselObjectId, string EnquiryID)
{
XLWorkbook exlWorkBook = null;
string FileName = "QuoteCompare_" + VesselObjectId + "_" + String.Format("{0:yyyyMMddHHmmss}", DateTime.Now) + ".xlsx";
string DirPath = Server.MapPath("~/App_Files/Seachef");
string FilePath = Path.Combine(DirPath, FileName);
string strTargetURL = GlobalParameters.SSRSBaseUrl + "/SeaChefReports/rptQuoteCompare&User_ID=" + CurrentUserData.UserId + "&P_ENQUIRY_HD_ID=" + EnquiryID + "&rc:LinkTarget=_blank&rc:Parameters=False&rs:Format=EXCELOPENXML&rs:ClearSession=true";
try
{
ReportViewer objReportViewer = new ReportViewer();
objReportViewer.ProcessingMode = ProcessingMode.Remote;
objReportViewer.ServerReport.ReportServerCredentials = new CustomReportCredentials(ConfigurationManager.AppSettings["ReportServerId"], ConfigurationManager.AppSettings["ReportServerPwd"], "BSM");
objReportViewer.ServerReport.Refresh();
SSRSWebClient client = new SSRSWebClient();
client.DownloadFileBinary(FilePath, strTargetURL);
if (new FileInfo(FilePath).Exists)
{
exlWorkBook = new XLWorkbook(FilePath);
var ws = exlWorkBook.Worksheet("rptQuoteCompare");
List<IXLCell> vendorsectionTotalCells = new List<IXLCell>();
List<IXLCell> vendorCategoryTotalCells = new List<IXLCell>();
ws.SheetView.FreezeRows(5);
ws.SheetView.FreezeColumns(7);
ws.Range(ws.FirstCell(), ws.LastCellUsed()).Style.Protection.Locked = true;
ws.Cell("A1").Value = EnquiryID;
//Doing Some more modifications
exlWorkBook.Style.Protection.Locked = true;
var protection = ws.Protect(BSMUiHelpers.SeachefSessionVariables.SeachefSessionData.ExcelPassword);
protection.SelectLockedCells = true;
protection.SelectUnlockedCells = true;
Stream objStream = new MemoryStream();
exlWorkBook.SaveAs(objStream);
objStream.Position = 0;
BinaryReader rdr = new BinaryReader(objStream);
byte[] fileData = rdr.ReadBytes((int)objStream.Length);
rdr.Close();
objStream.Close();
return File(fileData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", FileName);
}
else
{
return Json("Export failed!");
}
}
catch (Exception ex)
{
bool rethrow = UserInterfaceExceptionHandler.HandleExcetion(ref ex, CurrentUserData.UserId.ToString(), "");
return Json("Export failed!" + ex.Message);
}
finally
{
if (exlWorkBook != null)
exlWorkBook.Dispose();
if (new FileInfo(FilePath).Exists)
System.IO.File.Delete(FilePath);
}
}
below is the Stack Trace
at ClosedXML.Excel.XLWorkbook.LoadCells(SharedStringItem[] sharedStrings, Stylesheet s, NumberingFormats numberingFormats, Fills fills, Borders borders, Fonts fonts, Dictionary`2 sharedFormulasR1C1, XLWorksheet ws, Dictionary`2 styleList, Cell cell, Int32 rowIndex)
at ClosedXML.Excel.XLWorkbook.LoadRows(Stylesheet s, NumberingFormats numberingFormats, Fills fills, Borders borders, Fonts fonts, XLWorksheet ws, SharedStringItem[] sharedStrings, Dictionary`2 sharedFormulasR1C1, Dictionary`2 styleList, Row row)
at ClosedXML.Excel.XLWorkbook.LoadSpreadsheetDocument(SpreadsheetDocument dSpreadsheet)
at ClosedXML.Excel.XLWorkbook.LoadSheets(String fileName)
at ClosedXML.Excel.XLWorkbook.Load(String file)
at ClosedXML.Excel.XLWorkbook..ctor(String file, XLEventTracking eventTracking)
at ClosedXML.Excel.XLWorkbook..ctor(String file)
at BSM.BSMPALv2.Web.Areas.Seachef.Controllers.QuotationComparisionController.ExportToExcel(String VesselObjectId, String EnquiryID) in d:\XXX\TestSource\XXXXXXX.XXXXXX\XXXXXXX.XXXX\XXXXXXXXXX\Areas\ModuleName\Controllers\QuotationComparisionController.cs:line 293