add a row in an existing Excel file and save it - c#

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

Related

I want to create xlsx (Excel) file from c#

This is a code which could create only create xls file. But I want to create xlsx (Excel) file; how can I do that from this code or else can I have another code which I could use to create xlsx files.
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
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 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
xlWorkBook.SaveAs("d:\\vdfgdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, 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);
MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xls");
}
Please try below updated code.
public void CreateExcel()
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.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);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "1";
xlWorkSheet.Cells[2, 2] = "One";
xlWorkSheet.Cells[3, 1] = "2";
xlWorkSheet.Cells[3, 2] = "Two";
//Here saving the file in xlsx
xlWorkBook.SaveAs("d:\\vdfgdfg.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
MessageBox.Show("Excel file created , you can find the file d:\\csharp-Excel.xlsx");
}
Take a look on EasyXLS. It is a library that creates xlsx files.
ExcelDocument workbook = new ExcelDocument(1);
// Set the sheet name
workbook.easy_getSheetAt(0).setSheetName("Sheet1");
// Add data
ExcelTable xlsTable = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
xlsTable.easy_getCell(0, 0).setValue("ID");
xlsTable.easy_getCell(0, 1).setValue("Name");
xlsTable.easy_getCell(1, 0).setValue("1");
xlsTable.easy_getCell(1, 1).setValue("One");
xlsTable.easy_getCell(2, 0).setValue("2");
xlsTable.easy_getCell(2, 1).setValue("Two");
// Create Excel file
workbook.easy_WriteXLSXFile("d:\\vdfgdfg.xlsx");
See more at:
http://www.easyxls.com/manual/basics/create-excel-file.html
Try OpenXML library, should do the trick, find more at
Export DataTable to Excel with Open Xml SDK in c#
P.s. Interop won't work unless excel is installed on the machine.
Take a look at my SwiftExcel library. It was design for quick and easy excel output and what is more important - performance.
using (var ew = new ExcelWriter("C:\\temp\\test.xlsx"))
{
ew.Write("ID", 1, 1);
ew.Write("Name", 2, 1);
ew.Write("1", 1, 2);
ew.Write("One", 2, 2);
ew.Write("2", 1, 3);
ew.Write("Two", 2, 3);
}
Replace the following line:
xlWorkBook.SaveAs("d:\\vdfgdfg.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
with this line: xlWorkBook.SaveAs("d:\\vdfgdfg.xlsx");

How export textbox data into excel file?

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

Windows form application replaces each time the exported excel

I have wrote the following code for exporting my local database data to an excel file. The fact is that it is working properly, but I'd only like to export it with the actual date, or just month, like august, or something like that. Besides that, the problem that really matters is that it replaces every time the previously exported excel file. How can I change this thing? Thanks !
private void button3_Click_1(object sender, EventArgs e)
{
var connString = (#"Data Source=" + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)) + #"\Angajati.sdf");
using (var conn = new SqlCeConnection(connString))
{
try
{
conn.Open();
var query = "SELECT * FROM info ";
var command = new SqlCeCommand(query, conn);
var dataAdapter = new SqlCeDataAdapter(command);
var dataTable = new DataTable();
dataAdapter.Fill(dataTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Int16 i, j;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
for (i = 0; i <= dataGridView1.RowCount - 2; i++)
{
for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = dataGridView1[j, i].Value.ToString();
}
}
//adds column names to excel
string[] colNames = new string[dataGridView1.Columns.Count];
int col = 0;
foreach (DataGridViewColumn dc in dataGridView1.Columns)
colNames[col++] = dc.HeaderText;
char lastColumn = (char)(65 + dataGridView1.Columns.Count - 1);
xlWorkSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
xlWorkSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
xlWorkSheet.get_Range("A1", lastColumn + "1").VerticalAlignment
= Excel.XlVAlign.xlVAlignCenter;
xlWorkBook.SaveAs(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag\db.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("Salvat cu succes");
}
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();
}
}
If you don't want it to overwrite the same workbook every time then you'll need to specify a different file name rather than hard coding it in.
Something simple like creating the filename with the current datetime would normally be sufficient (you can change the format to suit you):
string fileName = #"db " + DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") + #".xls";
string filePath = Path.Combine(#"C:\Users\Andrei\Documents\Visual Studio 2010\Projects\Stellwag\Stellwag", fileName);
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
This would produce a file like this:
db 01-09-2015 10-32-35.xls
There is still not explicit check to see if the file exists, but unless you're clicking it every second it's unlikely to overwrite.

Rotate X axis in Excel chart c#

I'm trying to rotate the X-Axis text in an Excel chart.
Here is my current code:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int currentLine = 1;
foreach (int currentKey in currentLogFile.Keys)
{
xlWorkSheet.Cells[currentLine, 1] = currentKey;
xlWorkSheet.Cells[currentLine, 2] = currentLogFile[currentKey];
currentLine++;
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "B10");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
chartPage.ApplyLayout(6, Type.Missing);
xlWorkBook.SaveAs(excelOutputFile, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
I saw few solutions, like:
How to provide the custom angle to label in excel using C#
Changing Axis Labels on Excel Chart created in C#
C# chart rotate labels
However I get compilation errors on all of them.
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int currentLine = 1;
foreach (int currentKey in currentLogFile.Keys)
{
xlWorkSheet.Cells[currentLine, 1] = currentKey;
xlWorkSheet.Cells[currentLine, 2] = currentLogFile[currentKey];
currentLine++;
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "B10");
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;
//Rotate 35 degrees.
chartPage.Axes(Excel.XlAxisType.xlCategory).TickLabels.Orientation = 35;
chartPage.Axes(Excel.XlAxisType.xlValue).TickLabels.Orientation = 35;
chartPage.ApplyLayout(6, Type.Missing);
xlWorkBook.SaveAs(excelOutputFile, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

Programmatically alter an excel rows or columns heigh

Probably easy one. How can i change rows or column heigh?
xlApp = new Excel.Application();
xlApp.Visible = true;
xlApp.DisplayAlerts = false;
Excel.Workbooks xlWorkBooks = xlApp.Workbooks;
xlWorkBook = xlWorkBooks.Open(directoryPath + "\\" + fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
xlWorkSheets = xlWorkBook.Worksheets; //Get all the sheets in the workbook
xlWorkSheet = (Excel.Worksheet)xlWorkSheets.get_Item("Sheet1"); //Get the allready exists sheet
Excel.Range range = xlWorkSheet.UsedRange;
Excel.Range chartRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
xlWorkSheet.Cells[rowCount + 5, 1] = "Name and surname";
chartRange = xlWorkSheet.get_Range("a" + (rowCount + 5), "e" + (rowCount + 5));
chartRange.Font.Bold = true;
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(misValue, misValue, misValue);
xlWorkSheet = null;
xlWorkBook = null;
xlApp.Quit();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Try it with xlWorkSheet.UsedRange.EntireRow.Height = value; but it doesn't work. autoFit() is working but i would like to work with my value.
I think you may be looking for RowHeight...
http://msdn.microsoft.com/en-us/library/microsoft.office.tools.excel.namedrange.rowheight(v=vs.80).aspx

Categories

Resources