Can't write to excel using C#? - c#

I am writing a very simple program. It runs without any errors. But nothing is written into the Excel file. Am I wrong somewhere?
using Excel = Microsoft.Office.Interop.Excel;
// I already add this reference into my project
public Write()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\KKK.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
// This is all I want to write to my Excel file
xlWorkSheet.Cells[1, 1] = "input";
xlWorkBook.SaveAs(Directory.GetCurrentDirectory() + "\\KQ" + ThoiGian(), Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}

Try
xlWorkSheet.Cells[1, 1].value = "input";

Related

excelworkbook.saveas() throwing an error in c#

i have saw similar issues addressed in other questions but none helped me solve my particular issue although the exception is the same in all of the questions
this is the exception:
System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC
Message=The file could not be accessed. Try one of the following:
• Make sure the specified folder exists.
• Make sure the folder that contains the file is not read-only.
• Make sure the file name does not contain any of the following characters: < > ? [ ] : | or *
• Make sure the file/path name doesn't contain more than 218 characters.}
this is my code if you could point out my mistake and possibly the solution that would be much of a life saver.
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Excel is not properly installed!!");
return;
}
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1][1] = "total to pay";
xlWorkSheet.Cells[2][1] = "due before";
xlWorkSheet.Cells[1][lastUsedRow + 1] = richbox[11 + classnumber ].Text;
xlWorkSheet.Cells[2][lastUsedRow + 1] = Convert.ToString(DateTime.Today.Day) + "-" +Convert.ToString(DateTime.Today.AddMonths(1))+"-" +Convert.ToString(DateTime.Today.Year);
xlApp.DisplayAlerts = false;
xlWorkBook.SaveAs(#"C:\Users\Administrator\Desktop\coach ceazar\clients holds\test.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);

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

Range exception while saving data in Excel in Windows C#

Am trying to put in some data into excel cells. I get HResult rnge exception. below is the code. And also am not able to wrap the text in the cell [1,B] . am a fresher in using Office apps and not able to find a solution .
myExcelApp = new Excel.Application();
myExcelApp.Visible = true;
myExcelWorkbooks = myExcelApp.Workbooks;
String fileName1 = "D:\\book1.xlsx";
myExcelWorkbook = myExcelWorkbooks.Open(fileName1, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
Excel.Worksheet myExcelWorksheet = (Excel.Worksheet)myExcelWorkbook.ActiveSheet;
String cellFormulaAsString = myExcelWorksheet.get_Range("A2", misValue).Formula.ToString();
Microsoft.Office.Interop.Excel.Range range = myExcelWorksheet.UsedRange;
myExcelWorksheet.Cells[1, "A"] = text;
myExcelWorksheet.Cells[1, "B"] = commentText;
// myExcelWorksheet.Cells[1, "C"] = OccuranceList;
Excel.Range r = myExcelWorksheet.get_Range("B7", "A");
r.EntireRow.AutoFit();
Excel.Range r = myExcelWorksheet.get_Range("B7", "A");
You are missing a row number for Cell A
Something like this?
Excel.Range r = myExcelWorksheet.get_Range("B7", "A1");
FOLLOWUP
I just want to wrap text in cell[1,"B"] as the string is very large. – user1665707 59 mins ago
I dont get any error now. But the text wrapping is not happening. a part of the text is not visible. – user1665707 17 mins ago
Yes, it will not autofit. See this link for the reason.

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