how to read excel in silverlight - excel

For .xls files it's working fine,But .xlsx file i am getting following error
"An exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll but was not handled in user code".Let me know how to read .xlsx file.
OpenFileDialog oFile = new OpenFileDialog();
oFile.Filter = "Excel (*.xls)|*.xls";
if (oFile.ShowDialog() == true)
{
FileStream fs = oFile.File.OpenRead();
Workbook book = Workbook.Open(fs);
Worksheet sheet = book.Worksheets[0];
for (int i = sheet.Cells.FirstRowIndex; i < sheet.Cells.LastRowIndex; i++)
{
for (int j = sheet.Cells.FirstColIndex; j < sheet.Cells.LastColIndex; j++)
{
this.textBox1.Text += sheet.Cells[i, j].StringValue;
//this.textBox1.Text += ",";
}
this.textBox1.Text += Environment.NewLine;
}
}

Try flushing your filestream in the loop, then closing the file stream when you're done with it:
OpenFileDialog oFile = new OpenFileDialog();
oFile.Filter = "Excel (*.xls)|*.xls";
if (oFile.ShowDialog() == true) {
FileStream fs = oFile.File.OpenRead();
Workbook book = Workbook.Open(fs);
Worksheet sheet = book.Worksheets(0);
for (int i = sheet.Cells.FirstRowIndex; i <= sheet.Cells.LastRowIndex - 1; i++) {
for (int j = sheet.Cells.FirstColIndex; j <= sheet.Cells.LastColIndex - 1; j++) {
//this.textBox1.Text += ",";
this.textBox1.Text += sheet.Cells(i, j).StringValue;
fs.Flush();
}
this.textBox1.Text += Environment.NewLine;
}
fs.Close();
}
Also here: oFile.Filter = "Excel (*.xls)|*.xls"; you are just filtering to xls files

Related

export generated excel variable to real excel file

this is how I generated Excel variable:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
excelworkBook = excel.Application.Workbooks.Add(Type.Missing);
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
//proper data from xml data field to store in excel
// ************************
//generate a data table and fill excell cell
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1],
excelSheet.Cells[theDataSet.Tables[0].Rows.Count+1, theDataSet.Tables[0].Columns.Count]];
excelCellrange.Font.ThemeColor =
Microsoft.Office.Interop.Excel.XlThemeColor.xlThemeColorAccent1;
excelCellrange.EntireColumn.AutoFit();
Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
border.Weight = 3d;
excel.Columns.AutoFit();
excel.DisplayAlerts = false;
excel.Visible = true;
now the question is how save this excel variable to real excel file to specific destination ?
best regards.
this is how I figure out this problem that maybe help someone else:
Microsoft.Office.Interop.Excel.Application excel = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelworkBook;
Microsoft.Office.Interop.Excel.Worksheet excelSheet;
Microsoft.Office.Interop.Excel.Range excelCellrange;
excelworkBook = excel.Application.Workbooks.Add(Type.Missing);
excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
XmlDocument xml = new XmlDocument();
xml.LoadXml(dtAll.Rows[gridEX1.CurrentRow.RowIndex]["Data"].ToString());
StringReader theReader = new StringReader(xml.InnerXml);
DataSet theDataSet = new DataSet();
theDataSet.ReadXml(theReader);
excel.Caption = dtAll.Rows[gridEX1.CurrentRow.RowIndex]["docID"].ToString() + "_" + dtAll.Rows[gridEX1.CurrentRow.RowIndex]["DocTitle"].ToString() + "_" + dtAll.Rows[gridEX1.CurrentRow.RowIndex]["DocDetails"].ToString();
excel.StandardFont = "B Nazanin";
excel.StatusBar = "col count: " + theDataSet.Tables[0].Rows.Count;
for (int i = 0; i < theDataSet.Tables[0].Columns.Count; i++)
{
excel.Cells[1, i + 1] = theDataSet.Tables[0].Columns[i].ColumnName;
excel.Cells[1, i + 1].Font.Color = System.Drawing.Color.Blue;
for (int j = 0; j < theDataSet.Tables[0].Rows.Count; j++)
{
excel.Cells[j + 2, i + 1].Font.Color = System.Drawing.Color.Black;
excel.Cells[j + 2, i + 1] = theDataSet.Tables[0].Rows[j][i].ToString();
}
}
excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[theDataSet.Tables[0].Rows.Count + 1, theDataSet.Tables[0].Columns.Count]];
excelCellrange.Font.ThemeColor = Microsoft.Office.Interop.Excel.XlThemeColor.xlThemeColorAccent1;
excelCellrange.EntireColumn.AutoFit();
Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
border.Weight = 3d;
byte[] output = Encoding.UTF8.GetBytes(xml.InnerXml);
string strfn = GroupTitle + ".xlsx";
if (File.Exists(strfn))
{
File.Delete(strfn);
}
FileStream fs = new FileStream(strfn, FileMode.CreateNew, FileAccess.Write);
fs.Write(output, 0, output.Length);
fs.Flush();
fs.Close();
string dest = Global.DocOutputPath.Substring(0, Global.DocOutputPath.Length - 1) + GroupTitle + ".xlsx";
if (File.Exists(dest))
{
DialogResult dialogResult = MessageBox.Show("are you sure about rewrite on file?", "warnning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
File.Copy(strfn, dest);
File.Delete(dest);
}
else if (dialogResult == DialogResult.No)
{
return;
}
}
else
{
File.Copy(strfn, dest);
}

C# Deleting rows of excel sheet that contain variable not working

So below you will see the code im using to iterate through a excel spreadsheet and find every row that contains x. For some reason not only does the operation STOP at the very last row and not finish the operation, allowing me to save my edits and close the handle to excel, but also seems to be skipping rows. It will go through, say 25k rows that need to be deleted, yet only delete 12.5k. Im sure im doing something simple wrong here, so im hoping a few sets of eyes on it can spot my mistake. My code:
void startOperation()
{
Console.WriteLine("Beginning start operations..." + searchText);
Console.WriteLine("Opening Workbook: " + filePath);
// create excel-instance:
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
// open the concrete file:
Workbook xlWorkbook = xlApp.Workbooks.Open(#filePath);
//MessageBox.Show(filePath);
// select worksheet. NOT zero-based!!:
_Worksheet xlWorksheet = xlWorkbook.Sheets[1];
//MessageBox.Show(Convert.ToString(xlWorksheet.Name));
Microsoft.Office.Interop.Excel.Range range;
int numRows = xlWorksheet.UsedRange.Rows.Count;
numRowsDeleted = 0;
nullCounter = 0;
var percentageComp = new Decimal(.001);
//Parallel.For(1, numRows, new ParallelOptions { MaxDegreeOfParallelism = 1 }, i =>
for (currRow = 1; currRow <= numRows; currRow++)
{
percentageComp = ((decimal)currRow / (decimal)numRows) * 100;
Console.Clear();
Console.WriteLine("Number of Rows: " + numRows);
Console.WriteLine("Checking Row #: " + currRow);
Console.WriteLine("Number of Rows Deleted: " + numRowsDeleted);
Console.WriteLine("Percentage Comp: " + percentageComp.ToString("#.##"));
//Create Worksheet Range
range = (Microsoft.Office.Interop.Excel.Range)xlWorksheet.Cells[currRow, 2];
//MessageBox.Show(cellValue);
if (currRow == numRows)
{
closeOperation(xlApp, xlWorkbook);
break;
}
if (Convert.ToString(range.Value) != null) //if (cellValue != null || cellValue != "")
{
cellValue = Convert.ToString(range.Value);
//nullCounter = 0;
//MessageBox.Show("Cell Value: " + cellValue);
if (cellValue.Contains("MESSAGE NOT CONFIGURED"))
{
//MessageBox.Show("Cell Value: " + cellValue);
xlWorksheet.Rows[currRow].Delete(XlDeleteShiftDirection.xlShiftUp);
numRowsDeleted++;
//currRow++;
}
else
{
//currRow++;
}
}
else
{
//nullCounter++;
//currRow++;
}
//currRow++;
}
}
Again, your help is appreciated. Thanks!

Error while opening PPT File generated by Apache POI

I am generating a powerpoint presentation using apache POI - XSLF, on the fly when the user clicks a certain link on my website. I have a few tables with data on my presentation file and also an image (Line chart) generated using jfreechart. When I open the PPTX on my machine it seems to work fine. However when I open the file on another machine that has the powerpoint 2013, I get the following error.
"powerpoint found a problem with content powerpoint can attempt to repair the presentation".
I want to get rid of this error. I read on the internet that the solution is to "UNBLOCK" the powerpoint, which can be done through the properties section of the file. I am wondering if there's something I can do programmatically to suppress this errors for my users. This error message is annoying at the least.
My last thread on this was deleted - https://stackoverflow.com/questions/41163148/how-to-unblock-pptx-using-apache-poi
Hence re-creating this thread here again. A bug is also entered in bugzilla for apache POI. Bug Id - 60633 (https://bz.apache.org/bugzilla/show_bug.cgi?id=60633).
XSLFTableCell cell
XSLFTextParagraph p
XSLFTextRun line
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(X, Y, WIDTH, HEIGHT));
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(45);
//Loop through the data collection and populate rows and columns.
for(int i = 0; i < numberOfCols; i++) {
XSLFTableCell th = headerRow.addCell();
p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
line = p.addNewTextRun();.....}
for (int item=0; item < 8; item++)
{
XSLFTableRow itemRow = tbl.addRow();.....}
//finally write the file
File pptFile = File.createTempFile("fileName", ".ppt")
FileOutputStream out = new FileOutputStream(pptFile)
ppt.write(out)
out.close()
If one provides code along with a bug report, then this code must be complete and verifiable. Your code is not complete and verifiable. And if i do completing it, then it works without problems.
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
import org.apache.poi.sl.usermodel.TableCell.BorderEdge;
import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
import java.awt.Rectangle;
import java.awt.Point;
import java.awt.Color;
public class CreatePPTX {
public static void main(String[] args) throws Exception {
XMLSlideShow ppt = new XMLSlideShow();
XSLFSlide slide = ppt.createSlide();
XSLFTableCell cell;
XSLFTextParagraph p;
XSLFTextRun line;
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(new Point(100, 100)));
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(45);
for(int i = 0; i < 5; i++) {
XSLFTableCell th = headerRow.addCell();
p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
line = p.addNewTextRun();
line.setText("Header " + i);
th.setBorderWidth(BorderEdge.bottom, 2.0);
th.setBorderColor(BorderEdge.bottom, Color.black);
}
for (int item=0; item < 8; item++) {
XSLFTableRow itemRow = tbl.addRow();
for (int i = 0; i < 5; i++) {
XSLFTableCell td = itemRow.addCell();
p = td.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
line = p.addNewTextRun();
line.setText("Cell " + item + ":" +i);
}
}
FileOutputStream out = new FileOutputStream("fileName.pptx");
ppt.write(out);
out.close();
}
}
So your problem is not reproducible using the code you have provided.
But one thing can lead to your issue. If cells shall be empty in the table, then do not create empty runs but let the cell totally empty.
Example with the above code, if cell 1:1 shall be empty, then do not:
...
for (int item=0; item < 8; item++) {
XSLFTableRow itemRow = tbl.addRow();
for (int i = 0; i < 5; i++) {
XSLFTableCell td = itemRow.addCell();
p = td.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
line = p.addNewTextRun();
if (!(item==1 && i==1)) {
line.setText("Cell " + item + ":" +i);
}
}
}
...
This leads to the error.
Instead do:
...
for (int item=0; item < 8; item++) {
XSLFTableRow itemRow = tbl.addRow();
for (int i = 0; i < 5; i++) {
XSLFTableCell td = itemRow.addCell();
p = td.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
if (!(item==1 && i==1)) {
line = p.addNewTextRun();
line.setText("Cell " + item + ":" +i);
}
}
}
...

I tried with String Split with Varying number of elements in each row of data. I am not able to trace NULL at the end

Trying to read from a data file with number of rows of data and each row the number of elements are varying.
StreamReader read = new StreamReader("TextFile1.txt");
string str1 = " ";
while (str1 != null)
{
str1 = read.ReadLine();
if (str1 != null)
{
richTextBox1.AppendText("\n"+str1);
string[] s = str1.Split(' ');
i = 0;
sum = 0;
while (s[i] != null)
{
if(i>0)
j=int.Parse(s[i]);
sum = sum + j;
i = i + 1;
}
}
}
Presuming the code you posted is C#, you should use the String.length property.
Just a snippet of that from the inside of your loop:
string[] s = str1.Split(' ');
i = 0;
sum = 0;
while (i < s.length)
{
j=int.Parse(s[i]);
sum = sum + j;
i = i + 1;
}
By the way, I removed the if(i > 0) condition as it seems rather unnecessary. However, if you would like to exclude the first element on the line (which is what the if(i>0) condition was doing), then simply change i = 0; to i = 1;.

C++\CLI datagridview export to excel .xls file

The errors I have: don't create excel file just add another Microsoft excel in background process and saveFileDialog crash when I try to change file location:
saveFileDialog1->InitialDirectory = "C:";
saveFileDialog1->Title = "Save as Excel File";
saveFileDialog1->FileName = "";
saveFileDialog1->Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if(saveFileDialog1>ShowDialog()==System::Windows::Forms::DialogResult::OK){
Microsoft::Office::Interop::Excel::Application^ ExcelApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
ExcelApp->Workbooks->Add(Type::Missing);
for (int i = 1; i < datagridview1->Columns->Count + 1;i++)
{
ExcelApp->Cells[1, i] = datagridview1->Columns[i - 1]->HeaderText;
}
for (int i = 0; i < datagridview1->Rows->Count; i++)
{
for (int j = 0; j < datagridview1->Columns->Count; j++)
{
ExcelApp->Cells[i+2,j+1] = datagridview1->Rows[i]->Cells[j]->Value->ToString();
}
}
ExcelApp->ActiveWorkbook->SaveCopyAs(saveFileDialog1->FileName->ToString());
ExcelApp->ActiveWorkbook->Saved=true;
ExcelApp->Quit();
I had a similar problem once, the problem is in rows and cells writhing your datagridview1 into file. Code should look like this:
saveFileDialog1->Title = "Save as Excel File";
saveFileDialog1->FileName = "";
saveFileDialog1->Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
if(saveFileDialog1>ShowDialog()==System::Windows::Forms::DialogResult::OK){
Microsoft::Office::Interop::Excel::Application^ ExcelApp = gcnew Microsoft::Office::Interop::Excel::ApplicationClass();
ExcelApp->Workbooks->Add(Type::Missing);
for (int i = 1; i < datagridview1->Columns->Count + 1;i++)
{
ExcelApp->Cells[1, i] = datagridview1->Columns[i - 1]->HeaderText;
}
for (int i = 0; i < datagridview1->Rows->Count; i++)
{
for (int j = 0; j < datagridview1->Columns->Count; j++)
{
ExcelApp->Cells[i + 2, j + 1] = datagridview1->Rows[i]->Cells[j]->Value;
safe_cast<Range^>(ExcelApp->Cells[i + 2, j + 1]); }
}
ExcelApp->ActiveWorkbook->SaveCopyAs(saveFileDialog1->FileName->ToString());
ExcelApp->ActiveWorkbook->Saved=true;
ExcelApp->Quit();

Resources