I am trying to generate line chart from datatable but output is not coming fine. i guess there is axis related problem is there. so it will be great help if some one rectify my code.
private void button1_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = GetGraphData();
Excel.Application xla = new Excel.Application();
xla.Visible = true;
Excel.Workbook wb = xla.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = chartObjs.Add(250, 60, 300, 300);
Excel.Chart xlChart = chartObj.Chart;
int nRows = 2;
int nColumns = dt.Rows.Count;
string upperLeftCell = "B2";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1))
+ nRows - 1;
char endColumnLetter = System.Convert.ToChar(
Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}",
endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}",
endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = 1; i <= dt.Rows.Count; i++)
{
rg[1, i] = dt.Rows[i - 1][0].ToString(); //For Adding Header Text
rg[2, i] = int.Parse(dt.Rows[i - 1][1].ToString()); //For Adding Datarow Value
}
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, Type.Missing);
xlChart.ChartType = Excel.XlChartType.xlLine;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = "Project Status Graph";
// *****************Set legend:***************************
xlChart.HasLegend = true;
//FileStream file = new FileStream(#"d:\pop.xls", FileMode.Create);
//file.Close();
wb.SaveCopyAs(#"d:\pop.xls");
// ****************For Quiting The Excel Aplication ***********************
if (xla != null)
{
xla.DisplayAlerts = false;
wb.Close();
wb = null;
xla.Quit();
xla = null;
}
}
private System.Data.DataTable GetGraphData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("ProjectStatus"), new DataColumn("per") });
DataRow dr1 = dt.NewRow();
dr1[0] = "Compleet";
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Pending";
dr2[1] = 20;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "UnCompleet";
dr3[1] = 20;
dt.Rows.Add(dr3);
return dt;
}
i guess these below line are not fine.
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
//Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
// Excel.XlAxisGroup.xlPrimary);
//3d chart
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
this way i solved
this is just a sample code not real life implementation
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel;
using System.IO;
namespace WindowsForms_chartexcel
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add data
xlWorkSheet.Cells[1, 1] = "";
xlWorkSheet.Cells[1, 2] = "Student1";
xlWorkSheet.Cells[1, 3] = "Student2";
xlWorkSheet.Cells[1, 4] = "Student3";
xlWorkSheet.Cells[2, 1] = "Term1";
xlWorkSheet.Cells[2, 2] = "80";
xlWorkSheet.Cells[2, 3] = "65";
xlWorkSheet.Cells[2, 4] = "45";
xlWorkSheet.Cells[3, 1] = "Term2";
xlWorkSheet.Cells[3, 2] = "78";
xlWorkSheet.Cells[3, 3] = "72";
xlWorkSheet.Cells[3, 4] = "60";
xlWorkSheet.Cells[4, 1] = "Term3";
xlWorkSheet.Cells[4, 2] = "82";
xlWorkSheet.Cells[4, 3] = "80";
xlWorkSheet.Cells[4, 4] = "65";
xlWorkSheet.Cells[5, 1] = "Term4";
xlWorkSheet.Cells[5, 2] = "75";
xlWorkSheet.Cells[5, 3] = "82";
xlWorkSheet.Cells[5, 4] = "68";
Excel.Range chartRange ;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(200, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "d5");
chartPage.SetSourceData(chartRange, misValue);
//chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.ChartType = Excel.XlChartType.xlLine;
if (File.Exists(#"d:\test.xls"))
{
File.Delete(#"d:\test.xls");
}
xlWorkBook.SaveAs(#"d:\test.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
MessageBox.Show("Excel file created , you can find the file d:\test.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
Related
I'm having problems saving new rows in my existing Excel file, it throws an exception and says "write-protected". My Excel file is not open or something I created it with this code and saved it.
...
xlWorkBook.SaveAs(path, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
#endregion
endState = 7;
wasSuccessful = true;
Maybe I cant save it because it's open while I opened it to change it. So delete and save again maybe? or just save like you would save it after adding a row more in a normal Excel file and close it.
if (System.IO.File.Exists(path))
{
Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
//open existing Excel file
var wb = xlApp.Workbooks.Open(path, FileMode.Open, FileAccess.Read);
//get Sheet
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
//get the last Row who is filled
Excel.Range xlRange = (Excel.Range)ws.get_Range("A" + ws.Rows.Count, Type.Missing);
int LastRow = xlRange.get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
//def. next free row
int newRow = LastRow + 1;
//fill Cells
ws.Cells[newRow, 1] = LastRow - 3;
ws.Cells[newRow, 2] = BLZ;
ws.Cells[newRow, 3] = DK;
ws.Cells[newRow, 4] = KPA;
ws.Cells[newRow, 5] = Produktschlüssel;
ws.Cells[newRow, 6] = KMAUSTextressource;
ws.Cells[newRow, 7] = Versandschlüssel;
ws.Cells[newRow, 8] = Kartennummer;
ws.Cells[newRow, 9] = Verarbeitungshinweis;
ws.Cells[newRow, 10] = Anrede;
ws.Cells[newRow, 11] = Kundenname1;
ws.Cells[newRow, 12] = Kundenname2;
ws.Cells[newRow, 13] = AnschriftZusatz;
ws.Cells[newRow, 14] = Straße;
ws.Cells[newRow, 15] = PLZuWohnort;
ws.Cells[newRow, 16] = alternativAusland;
ws.Cells[newRow, 26] = BLZ;
ws.Cells[newRow, 27] = DK;
xlApp.DisplayAlerts = false;
wb.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
wb.Close(true, path);
//wb.Close(true, misValue, misValue);
xlApp.Quit();
}
FileAccess.Read?
//open existing Excel file
var wb = xlApp.Workbooks.Open(path, FileMode.Open, FileAccess.Read);
I've things work with just:
Excel.Workbook workbook = excel.Workbooks.Open(#"C:\MyExcelFile.xlsx"); // No other arguments
Complete version:
using Excel = Microsoft.Office.Interop.Excel;
void DoWorkWithExcel()
{
Excel.Application excel = null;
Excel.Workbook workbook = null;
Excel.Worksheet worksheet = null;
string excelFile = #"C:\MyExcelFile.xlsx";
try
{
excel = new Excel.Application { Visible = true, DisplayAlerts = false };
workbook = excel.Workbooks.Open(excelFile);
worksheet = (Excel.Worksheet)workbook.Worksheets[1];
int newRow = worksheet.Range["A" + worksheet.Rows.Count, Type.Missing]
.End[Excel.XlDirection.xlUp].Row + 1;
// Fill you cells
worksheet.Cells[newRow, 1] = newRow - 4; // Your LastRow + 1 - 3;
worksheet.Cells[newRow, 2] = BLZ;
worksheet.Cells[newRow, 3] = DK;
// And others...
// Save changes
workbook.Save();
}
catch (Exception ex) // Or System.Runtime.InteropServices.COMException
{
// Handle it or log or do nothing
}
finally
{
// Close Book and Excel and release COM Object
workbook?.Close(0);
excel?.Quit();
Marshal.ReleaseComObject(excel);
}
}
How to set the user-defined color for series, not able to figure it out, Please help
private void button1_Click(object sender, EventArgs e) {
Microsoft.Office.Interop.Excel.Application excelWrite = new Microsoft.Office.Interop.Excel.Application();
// Create empty workbook
excelWrite.Workbooks.Add();
// Create Worksheet from active sheet
Microsoft.Office.Interop.Excel._Worksheet workSheet = excelWrite.ActiveSheet;
workSheet.Name = "Result";
workSheet.Cells[1, "A"] = "Color";
workSheet.Cells[2, "A"] = "R";
workSheet.Cells[3, "A"] = "G";
workSheet.Cells[4, "A"] = "B";
workSheet.Cells[1, "B"] = "Brown";
workSheet.Cells[1, "C"] = "Pink";
workSheet.Cells[1, "D"] = "Silver";
workSheet.Cells[2, "B"] = 40;
workSheet.Cells[3, "B"] = 26;
workSheet.Cells[4, "B"] = 13;
workSheet.Cells[2, "C"] = 100;
workSheet.Cells[3, "C"] = 75;
workSheet.Cells[4, "C"] = 80;
workSheet.Cells[2, "D"] = 75;
workSheet.Cells[3, "D"] = 75;
workSheet.Cells[4, "D"] = 75;
Microsoft.Office.Interop.Excel.Range xlRange = workSheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
Microsoft.Office.Interop.Excel.ChartObjects xlCharts = (Microsoft.Office.Interop.Excel.ChartObjects)workSheet.ChartObjects(Type.Missing);
Microsoft.Office.Interop.Excel.ChartObject myChart = (Microsoft.Office.Interop.Excel.ChartObject)xlCharts.Add(150, 150, 800, 350);
Microsoft.Office.Interop.Excel.Chart chartPage = myChart.Chart;
chartPage.SetSourceData(xlRange, Type.Missing);
chartPage.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlBarStacked100;
chartPage.AutoScaling = true;
Microsoft.Office.Interop.Excel.ChartClass cc = myChart.
excelWrite.DisplayAlerts = false;
workSheet.SaveAs(#"C:\Users\apex\Desktop\" + "Result_ForChart_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx");
ClearAllEndAll(excelWrite, workSheet);
Defeat();
}
Is it possible to do with interop, if not Please suggest other nuget/lib to be used
Have you tried EPPlus? It's an OOXML wrapper that allows you to create Excel spreadsheets with ease. It is available via NuGet or on github (https://github.com/JanKallman/EPPlus).
Edit - Here is a code sample:
using (FileStream stream = new FileStream("test.xlsx", FileMode.Create))
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("My Data");
Color bgcolor = ColorTranslator.FromHtml("#00FFFF");
worksheet.Cells["A1:B1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor(bgcolor);
worksheet.Cells["A1"].Value = "Hello";
worksheet.Cells["B1"].Value = "World!";
package.SaveAs(stream);
}
Hi i try to get better with the c# excel stuff. Right now i try to select some values from an existing excelsheet. For Example: From B4 to C16. So i can replace the values with something else but i dont get it to work.
This is my little method:
public void writeExcelFile()
{
string path = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Excel.Worksheet)mWorkSheets.get_Item(1);
//Excel.Range range = mWSheet1.UsedRange;
//int colCount = range.Columns.Count;
//int rowCount = range.Rows.Count;
int countRows = mWSheet1.UsedRange.Rows.Count;
int countColumns = mWSheet1.UsedRange.Columns.Count;
object[,] data = mWSheet1.Range[mWSheet1.Cells[1, 1], mWSheet1.Cells[countRows, countColumns]].Cells.Value2;
for (int index = 1; index < 15; index++)
{
mWSheet1.Cells[countRows + index, 1] = countRows + index;
mWSheet1.Cells[countRows + index, 2] = "test" + index;
}
//Excel.Worksheet sheet = workbook.ActiveSheet;
//Excel.Range rng = (Excel.Range)sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3, 3]);
mWorkBook.SaveAs(path, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive,Missing.Value, Missing.Value, Missing.Value,Missing.Value, Missing.Value);
mWorkBook.Close(Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
I tried it with get_range but i get an exception that this is not aviable.
It has something to do with the Microsoft.Office.Interop libary 14. Then i tried it with object[,] but the only thing i got to work is that after all used cells to insert test but not to select anything. So any help would be great.
Thanks for your Time and sorry for my english.
EDIT: At least the read process works now and i loop trough a selected range.
Here is the working code:
public void writeExcelFile()
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open the Excel File
Excel.Workbook oWB = oXL.Workbooks.Open(inputFile);
String SheetName = "Gesamt";
Excel._Worksheet oSheet = oWB.Sheets[SheetName];
String start_range = "B4";
String end_range = "R81";
Object[,] values = oSheet.get_Range(start_range, end_range).Value2;
int t = values.GetLength(0);
for (int i = 1; i <= values.GetLength(0); i++)
{
String val = values[i, 1].ToString();
}
oXL.Quit();
}
After many tries i finnaly got a working solution where i can select any cells i want. Maby there are better ways but for me it works as expected.
the code:
public void writeExcelFile()
{
try
{
String inputFile = #"C:\Users\AAN\Documents\Visual Studio 2015\Projects\WorkWithExcel\WorkWithExcel\bin\Debug\PROJEKTSTATUS_GESAMT_neues_Layout.xlsm";
Excel.Application oXL = new Excel.Application();
#if DEBUG
oXL.Visible = true;
oXL.DisplayAlerts = true;
#else
oXL.Visible = false;
oXL.DisplayAlerts = false;
#endif
//Open a Excel File
Excel.Workbook oWB = oXL.Workbooks.Add(inputFile);
Excel._Worksheet oSheet = oWB.ActiveSheet;
List<String> Name = new List<String>();
List<Double> Percentage = new List<Double>();
Name.Add("Anil");
Name.Add("Vikas");
Name.Add("Ashwini");
Name.Add("Tobias");
Name.Add("Stuti");
Name.Add("Raghavendra");
Name.Add("Chithra");
Name.Add("Glen");
Name.Add("Darren");
Name.Add("Michael");
Percentage.Add(78.5);
Percentage.Add(65.3);
Percentage.Add(56);
Percentage.Add(56);
Percentage.Add(97);
Percentage.Add(89);
Percentage.Add(85);
Percentage.Add(76);
Percentage.Add(78);
Percentage.Add(89);
oSheet.Cells[1, 1] = "Name";
oSheet.Cells[1, 2] = "Percentage(%)"; // Here 1 is the rowIndex and 2 is the columnIndex.
//Enter the Header data in Column A
int i = 0;
for (i = 0; i < Name.Count; i++)
{
oSheet.Cells[i + 2, 1] = Name[i];
}
//Enter the Percentage data in Column B
for (i = 0; i < Percentage.Count; i++)
{
oSheet.Cells[i + 2, 2] = Percentage[i];
}
oSheet.Cells[Name.Count + 3, 1] = "AVERAGE";
//Obtain the Average of the Percentage Data
string currentFormula = "=AVERAGE(B2:" + "B" + Convert.ToString(Percentage.Count + 1) + ")";
oSheet.Cells[Percentage.Count + 3, 2].Formula = currentFormula;
//Format the Header row to make it Bold and blue
oSheet.get_Range("A1", "B1").Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.AliceBlue);
oSheet.get_Range("A1", "B1").Font.Bold = true;
//Set the column widthe of Column A and Column B to 20
oSheet.get_Range("A1", "B12").ColumnWidth = 20;
//String ReportFile = #"D:\Excel\Output.xls";
oWB.SaveAs(inputFile, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
Type.Missing, Type.Missing,
false,
false,
Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing);
oXL.Quit();
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
oSheet = null;
oWB = null;
oXL = null;
GC.GetTotalMemory(false);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.GetTotalMemory(true);
}
catch (Exception ex)
{
String errorMessage = "Error reading the Excel file : " + ex.Message;
MessageBox.Show(errorMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
This is not my own code its from a blog: the blog where i got it just edited so it works for me.
I created a WinForm that adds data from textboxs to a List and then when the form closes, exports that data to an excel spreadsheet. I'm in the process of trying to convert my WinForm to a WPF, and the code is no longer working. I'm not getting any errors, it just isn't creating the spreadsheet. Am I missing something here?
protected void OnFormClosing(object sender, EventArgs e)
{
if(signees.Count > 0)
{
initExcelSheet();
}
}
public void initExcelSheet()
{
EXL.Application oXL;
EXL._Workbook oWB;
EXL._Worksheet oWS;
EXL.Range oRng;
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
//Get a new workbook.
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
oWS = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
oWS.Cells[1, 1] = "First Name";
oWS.Cells[1, 2] = "Last Name";
oWS.Cells[1, 3] = "Email";
oWS.Cells[1, 4] = "Expected Graduation Date";
oWS.Cells[1, 5] = "School";
oWS.Cells[1, 6] = "Major";
oWS.Cells[1, 7] = "Favorite Languages";
oWS.get_Range("A1", "G1").Font.Bold = true;
oWS.get_Range("A1", "G1").VerticalAlignment =
Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;
int count = 2;
foreach(Person x in signees)
{
oWS.Cells[count, 1] = x.firstName;
oWS.Cells[count, 2] = x.lastName;
oWS.Cells[count, 3] = x.email;
oWS.Cells[count, 4] = x.gradDate.ToString("yyyy-MM-dd");
oWS.Cells[count, 5] = x.schoolName;
oWS.Cells[count, 6] = x.fos;
oWS.Cells[count, 7] = x.fcl;
count += 1;
}
oRng = oWS.get_Range("A1", "G1");
oRng.EntireColumn.AutoFit();
try
{
oWB.SaveAs(fileName(school, DateTime.Now));
}
catch(Exception e)
{
Console.Write(e.ToString());
}
oWB.Close();
First i apologize for the mistakes in my text, english is not my native language and i do my best.
I'm a very beginner in coding and i have a little question about loading an excel sheet.
I'm trying to do a project with vb in c# and i have to load an excel sheet which already exist and write in it. I found some explanations who help me to create a New sheet and write in it :
private void button1_Click(object sender, System.EventArgs e)
{
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;
try
{
oXL = new Excel.Application("Exemple.xlsx");
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
oSheet.Cells[1, 1] = "First Name";
oSheet.Cells[1, 2] = "Last Name";
oSheet.Cells[1, 3] = "Full Name";
oSheet.get_Range("A1", "C1").Font.Bold = true;
oSheet.get_Range("A1", "C1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;
string[,] saNames = new string[5, 2];
saNames[0, 0] = "John";
saNames[0, 1] = "Smith";
saNames[1, 0] = "Tom";
saNames[1, 1] = "Brown";
saNames[2, 0] = "Sue";
saNames[2, 1] = "Thomas";
saNames[3, 0] = "Jane";
saNames[3, 1] = "Jones";
saNames[4, 0] = "Adam";
saNames[4, 1] = "Johnson";
oSheet.get_Range("A2", "B6").Value2 = saNames;
oRng = oSheet.get_Range("C2", "C6");
oRng.Formula = "=A2 & \" \" & B2";
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
The things i write don't really matter but i can't load my own sheet. I tought by replacing
oXL = new Excel.Application();
by
oXL = new Excel.Application("Exemple.xlsx");
I could load my sheet ( call Exemple.xlsx)
Unfortunately it don't work, could you tell me what's wrong?
Thanks!
Once you have your reference to Excel, you must call the Workbooks.Open method to open an existing file:
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Open("Example.xlsx"));