I have 2 textbox i.e. textbox1,textbox2
I want to export the data from these textboxes to an excel sheet i.e. test.xlsx
using a button.
Anyone know what's the code to do that?
First, you need to add a reference to the Excel Object Library in your project.
You can than import the library to your form:
using Excel = Microsoft.Office.Interop.Excel;
You can add similar code to this:
var excelApp = new Excel.Application();
excelApp.Workbooks.Open(filePath);
Excel._Worksheet workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
workSheet.Cells[1, "A"] = textBox1.Text;
workSheet.Cells[1, "B"] = textBox1.Text;
You can also check this Walkthrough for an detailed explanation
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
string myPath = tbFolderpath.Text + tbFileName.Text;//User Given Path Value
FileInfo fi = new FileInfo(myPath);
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (!fi.Exists)//To Check File exist in a location,if not exist it will create new file
{
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, "A"] = "Name";
xlWorkSheet.Cells[1, "B"] = "Age";
xlWorkSheet.Cells[1, "C"] = "CurrentTime";
var columnHeadingsRange = xlWorkSheet.Range[xlWorkSheet.Cells[1, "A"],
xlWorkSheet.Cells[1, "C"]];
columnHeadingsRange.Interior.Color = Excel.XlRgbColor.rgbYellow;//To Give Header Color
xlWorkBook.SaveAs(myPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook,
misValue,misValue, misValue, misValue,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
misValue, misValue, misValue, misValue, misValue);
}
//Already File Exist it will open the File and update the data into excel`enter code here`
var workbook = xlApp.Workbooks.Open(myPath);
xlWorkSheet = (Excel.Worksheet)workbook.Worksheets.get_Item(1);
int _lastRow = xlWorkSheet.Range["A" +xlWorkSheet.Rows.Count].
End[Excel.XlDirection.xlUp].Row + 1;
xlWorkSheet.Cells[_lastRow, "A"] = Textbox1.Text;
xlWorkSheet.Cells[_lastRow, "B"] = Textbox2.Text;
DateTime currentTime = DateTime.Now;//To Get the Current Time
string formattedTime = currentTime.ToString("dd/MM/yyyy-hh:mm:ss");
xlWorkSheet.Cells[_lastRow, "C"] = formattedTime;
workbook.Save();
workbook.Close();
xlApp.Quit();
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);
}
}
EDIT:
I am trying to use Microsoft Excel in Visual Studio C#.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace write_data_to_excel
{
class Program
{
static void Main(string[] args)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
xlWorkBook.SaveAs("C:\\examplewrite.xlsx", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
}
}
Error:
System.Runtime.InteropServices.COMException: 'Cannot access 'examplewrite.xlsx'.'
I am using VS Community 2017.
Yeah, it requires that all client machines have the same version of Microsoft Excel installed unfortunately.
more info found here: https://www.gemboxsoftware.com/spreadsheet/articles/c-sharp-microsoft-office-interop-excel-automation
I'm creating a windows service that will create excel sheets, I've used Microsoft.Office.Interop.Excel but got this Exception
Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE
I've attached a photo here
Exception photo attached
public void insertIntoSheet(string Name, DataTable dt)
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
//MessageBox.Show("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (int i = 1, j = 0; j < dt.Rows.Count; i++, j++)
{
xlWorkSheet.Cells[i, 1] = dt.Rows[j][0].ToString();
xlWorkSheet.Cells[i, 2] = dt.Rows[j][1].ToString();
xlWorkSheet.Cells[i, 3] = dt.Rows[j][2].ToString();
xlWorkSheet.Cells[i, 4] = dt.Rows[j][3].ToString();
xlWorkSheet.Cells[i, 5] = dt.Rows[j][4].ToString();
xlWorkSheet.Cells[i, 6] = dt.Rows[j][5].ToString();
}
//xlWorkSheet.Cells[1, 1] = "Sheet 1 content";
xlWorkBook.SaveAs(String.Format("d:\\{0}.xls", Name), 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);
Class_Library.WriteErrorLog("Inserting the sheet method finished");
//MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Class_Library.WriteErrorLog(ex.Message);
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
NOTES: I've used the same code as a test in windows application and it worked as expected.
I've tried to write Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); and also tried to use the Name Excel only like Excel.Application xlApp = new Excel.Application();
Try Edit DCOMConfig
1.In DCOMCNFG, right click on the My Computer and select properties.
2.Go to Component /MyComputer/DCOMConfig
3.Go to Microsoft Excel Application property Security
4.In launch and Activation Permissions, click "Custamize" and add Network
Service to it and give it "Local launch" and "Local Activation" permission. give same As Acess Permissions and cofiguration Permissions Press OK and thats it. You can run my application now.
Go to Excel's options / trust center / Macro settings and check "Trust access to the VBA project object model"
I have a file Excel contains 4 Sheets, how can I write data to sheet 2 without using OLEDB, and I want to write data cell by cell...
Could any one help me ?
I have a code like this :
Excel._Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
private void button1_Click(object sender, EventArgs e)
{
Excel._Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open("E:\\Project Skripsi\\normalisasi.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1].Value2 = Convert.ToInt32(xlWorkSheet.Cells[1, 1].Value2) + 1;
xlWorkBook.Close(false, misValue, misValue);
xlApp.Quit();
}
For using worksheet 2 you will have to use this..
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
This means that xWorkSheet object is pointing to the sheet2 and values you added to the cells would be added to sheet2.
And u can add values to cells using this,
xlWorkSheet.Cells[1, 1] = "YourValue(Could be of any data type)";
With Office-Interop you can access the different sheets by using the index on the Worksheet-property in the Workbook object:
//select the first sheet
Excel.Worksheet sheet1 = (Worksheet) xlWorkBook.Worksheets[1];
//select the second sheet
Excel.Worksheet sheet2 = (Worksheet) xlWorkBook.Worksheets[2];
I have created a spread sheet (Example for MSDN) and now I want to populate data from a dataset to this sheet. Once the data is populated than I want to draw chart on the basis of available data. I dont want to use Pivot Table, I just want to draw chart whatever data is comming from dataset.I have never worked with spreadsheets before and can't find a right example to get some help from.
I have two Questions here
How to populate data in SpreadSheet from dataset
How to draw chart (Any chart example) on the basis of available data
Anyone's help will really be appriciated.
Following is my code snippet
Public void CreateSpreadSheet()
{
DataSet dataSet = GetDatasetForSpreadSheetChart();
int noOfRows = dataSet.Tables["SpreadSheetTestTable"].Rows.Count;
int noOfColumns = dataSet.Tables["SpreadSheetTestTable"].Columns.Count;
// Create a spreadsheet document by supplying the filepath.
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filePath,SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),SheetId = 1,Name = "mySheet"
};
sheets.Append(sheet);
// Get data from dataset and insert it in spreadsheet
SheetData sheetData = sheet.GetFirstChild<SheetData>();
for (int c = 0; c < noOfColumns; c++)
{
string headerName = dataSet.Tables["SpreadSheetTestTable"].Columns[c].ToString();
}
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}
public void CreateExcelDocFromDatatable(DataTable dataTable)
{
object misValue = System.Reflection.Missing.Value;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int iCol = 0;
foreach (DataColumn c in dataTable.Columns)
{
iCol++;
xlWorkSheet1.Cells[1, iCol] = c.ColumnName;
}
int iRow = 0;
foreach (DataRow r in dataTable.Rows)
{
iRow++;
iCol = 0;
foreach (sd.DataColumn c in mdtOutput.Columns)
{
string cellData = r[c.ColumnName].ToString();
iCol++;
xlWorkSheet1.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
xlWorkSheet1.Activate();
var range = xlWorkSheet1.get_Range("2:2",misValue);
range.Select();
xlApp.ActiveWindow.FreezePanes = true;
range = xlWorkSheet1.get_Range("1:1", misValue);
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
mXlWorkBook.SaveAs(outputFilePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlApp.Visible = true;
xlWorkSheet1.Activate();
}
private void CreateExcelCharts()
{
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet chartsSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
chartsSheet.DisplayRightToLeft = false;
chartsSheet.Name = "Charts";
Excel.ChartObjects chartObjs = (Excel.ChartObjects)chartsSheet.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = chartObjs.Add(200, 40, 300, 300);
Excel.Chart xlChart = chartObj.Chart;
Excel.Range range = chartsSheet.get_Range("B2", "C7");
xlChart.SetSourceData(range, misValue);
xlChart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xl3DPie;
mXlWorkBook.Save();
}
Then you can play with the chart properties, where you'd be able to control practically everything as from Excel UI (chart title, axes, gridlines, colors, etc.)
I have found a very good solution for this scenario. Table in Excel can be drawn from the following link
http://www.nitrix-reloaded.com/2010/09/26/creating-excel-files-from-dataset-using-openxml-20-c-sharp/
and than by using http://spreadsheetlight.com/ Libraries any type of chart/graph can be drawn in Excel.
Changes can be made according to the scenario. Such as supplying starting and ending cell values for chart creation etc. In my scenario I have worked with run time values where I am not aware of what and how many columns are there in my Excel table. I can provide the code snippet of my scenario, if anyone needs it.
Regards!