export generated excel variable to real excel file - excel

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);
}

Related

Add and view dataLabels (CTDLbls) in lineChart excel graph

I've developed the following code, but is not fully acomplishing what I need.
I would like to have the chance to set some specific datalabels of this serie
public static void main(String[] args) {
Workbook wb = new XSSFWorkbook();
Sheet dataSheet = wb.createSheet("linechart");
final int NUM_OF_ROWS = 10;
final int NUM_OF_COLUMNS = 4;
Row row;
Cell cell;
for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
row = dataSheet.createRow((short) rowIndex);
for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
if (colIndex<3) {
cell = row.createCell((short) colIndex);
cell.setCellValue(rowIndex * ((colIndex + 1) + ((int) (Math.random() * 10))));
}
else{
if (rowIndex == 0){
cell = row.createCell((short) colIndex);
cell.setCellValue("This is the first comment");
}
else if (rowIndex == 3){
cell = row.createCell((short) colIndex);
cell.setCellValue("This is another comment");
}
}
}
}
Drawing drawing = dataSheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, NUM_OF_COLUMNS + 2, 3, NUM_OF_COLUMNS + 15, 20);
//XSSFChart xlsxChart = XSSFChart.createChart();
Chart chart = drawing.createChart(anchor);
ChartLegend legend = chart.getOrCreateLegend();
legend.setPosition(LegendPosition.RIGHT);
LineChartData data = chart.getChartDataFactory().createLineChartData();
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
ChartDataSource<Number> xs = DataSources.fromNumericCellRange(dataSheet, new CellRangeAddress(0, NUM_OF_ROWS - 1, 0, 0));
ChartDataSource<Number> ys1 = DataSources.fromNumericCellRange(dataSheet, new CellRangeAddress(0, NUM_OF_ROWS - 1, 1, 1));
ChartDataSource<Number> ys2 = DataSources.fromNumericCellRange(dataSheet, new CellRangeAddress(0, NUM_OF_ROWS - 1, 2, 2));
// Not used: ChartDataSource<String> ys3 = DataSources.fromStringCellRange(dataSheet, new CellRangeAddress(0, NUM_OF_ROWS - 1, 3, 3));
LineChartSeries series1 = data.addSeries(xs, ys1);
series1.setTitle("one");
LineChartSeries series2 = data.addSeries(xs, ys2);
series2.setTitle("two");
chart.plot(data, bottomAxis, leftAxis); // creating the basics of the graph
XSSFChart xssfChart = (XSSFChart) chart;
CTPlotArea plotArea = xssfChart.getCTChart().getPlotArea();
CTBoolean ctBool = CTBoolean.Factory.newInstance();
ctBool.setVal(true);
plotArea.getLineChartArray(0).getSerArray(0).addNewDLbls().setShowVal(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().addNewShowLeaderLines();
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowLeaderLines(ctBool);
ctBool.setVal(false);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowSerName(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowPercent(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowLegendKey(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowCatName(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowLeaderLines(ctBool);
plotArea.getLineChartArray(0).getSerArray(0).getDLbls().setShowBubbleSize(ctBool);
// Adding "markers" on each point
CTMarker ctMarker = CTMarker.Factory.newInstance();
ctMarker.setSymbol(CTMarkerStyle.Factory.newInstance());
for (CTLineSer ser : plotArea.getLineChartArray()[0].getSerArray()) {
ser.setMarker(ctMarker);
}
try{
FileOutputStream fileOut = new FileOutputStream("D:" + File.separator + "stack_v2.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Generating the following output
Output from the code
But what I want, is having the showLeaderLines option activated inside the CDTLbsls structure
See the following desired output:
Desired output
I need help on:
Clarifying Apache-POI classes involved (CDTLbl, CDTLbls, CTLine, DLbl & DLbls)
How to achieved the ShowLeaderLines functionality
How to set specific content rather than the value
Located them at a specific point of the graph (as you may see, I would like to add it close to the top)
In the end, I find it was not possible to achieve the same functionality as with MS Office 2016 because the libs are not enough developed.
Ways tried between others was modifying directly the XML output... but some tags are not available yet.

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!

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();

Accessing 3DPie Chart using Interop in c#

/* Im creating a 3D Pie Chart using the code below. It works fine. The program export the Excel File. What i want to happen now is to disable the Category Name and Value Data Labels. And i want to change the Separator to New Line. How would i do it? Can someone help me with this? Please. Your help will be so much appreciated. Please refer from my codes below. */
private void btnGenerateChart_Click(object sender, EventArgs e){
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
int x = 2;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
// Create and select 1st sheet
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
try{
SqlCommand compass = _SqlConnection._SqlCon.CreateCommand();
compass.CommandText = ''sp_SelectRawData'';
compass.CommandType = CommandType.StoredProcedure;
_SqlConnection._SqlCon.Open();
SqlDataReader dreader = compass.ExecuteReader();
xlWorkSheet.Cells[1, 2] = ''Tag I - IV'';
xlWorkSheet.Cells[1, 3] = ''Tag V'';
xlWorkSheet.Cells[1, 4] = ''No Tag'';
while(dreader.Read()){
xlWorkSheet.Cells[x, 1] = dreader.ToString();
xlWorkSheet.Cells[x, 2] = dreader.ToString();
xlWorkSheet.Cells[x, 3] = dreader.ToString();
xlWorkSheet.Cells[x, 4] = dreader.ToString();
x++;
}
dreader.Close();
_SqlConnection._SqlCon.Close();
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
// Chart range is used to select cells
Excel.Range chartRange;
chartRange = xlWorkSheet.get_Range(''A1'', ''D'' + (x - 1));
chartRange.Columns.EntireColumn.AutoFit();
chartRange = xlWorkSheet.get_Range(''B2'', ''D'' + (x - 1));
chartRange.Columns.NumberFormat = ''_(#,##0.00_);_((#,##0.00);_(\''-\''??_);_(#_)'';
// Create and select 2nd sheet
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
// Chart size
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 10, 750, 350);
Excel.Chart chartPage = myChart.Chart;
chartPage.HasLegend = true;
chartPage.ChartTitle.Text = ''Final IAS Provition'';
var xAxis = (Excel.Axis)chartPage.Axes(Excel.XlAxisType.xlValue, Excel.XlAxisGroup.xlPrimary);
xAxis.HasTitle = true;
xAxis.AxisTitle.Text = ''Scale Value'';
var yAxis = (Excel.Axis)chartPage.Axes(Excel.XlAxisType.xlCategory, Excel.XlAxisGroup.xlPrimary);
yAxis.HasTitle = true;
yAxis.AxisTitle.Text = ''Originating Unit'';
// Refer chart data source from the1st sheet
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
chartRange = xlWorkSheet.get_Range(''A1'', ''D'' + (x - 1));
// Go to sheet two
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
// Set chart data source
chartPage.SetSourceData(chartRange, misValue);
chartPage.ApplyDataLabels();
chartPage.ChartType = Excel.XlChartType.xl3DPie;
chartPage.Rotation = 0;
chartPage.Perspective = Convert.ToInt16(0.1);
xlWorkBook.CheckCompatibility = false;
chartRange.Worksheet.Protect(Password: ''987654321'', AllowFormattingColumns: true, AllowFiltering: true);
xlWorkBook.SaveAs(yourpath + ''.xls'', Excel.XlFileFormat.xlWorkbookNormal, ''123'', misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj){
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch(Exception ex){
obj = null;
}
finally{
GC.Collect();
}
}

how to read excel in silverlight

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

Resources