Save an excel file in c# - c#

void excelsave()
{
try
{
ApplicationClass app = new ApplicationClass(); // the Excel application.
Workbook book = null;
Worksheet sheet = null;
Range range = null;
// the range object is used to hold the data
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
string execPath =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
book = app.Workbooks.Open(#"E:\SSIS\ABC\Book1.xls",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
range = sheet.get_Range("A1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
range = sheet.get_Range("B1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
book.SaveAs(#"E:\SSIS\ABC\Book1.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
}
}
Here I am opening an excel sheet trying to increase the column width and need to make the column headers as bold and save the document, right now the document is not getting saved. I am using vs 2008, c# 3.5
Is There anything that I am doing wrong here? any help on this would be great
looking an for solution

I ran the following using VS 2010 and .NET 4, but this code should still work in your environment. Also, I simplified your code a bit. Hopefully this will get you going in the right direction.
static void excelsave()
{
try
{
Application app = new Application();
string execPath =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
Workbook book = app.Workbooks.Open(#"c:\test.xls");
Worksheet sheet = (Worksheet)book.Worksheets[1];
Range range = sheet.get_Range("A1");
range.Columns.ColumnWidth = 22.34;
range = sheet.get_Range("B1");
range.Columns.ColumnWidth = 22.34;
sheet.get_Range("A1", "B1").Font.Bold = true;
book.SaveAs(#"c:\test2.xls"); // or book.Save();
book.Close();
}
catch (Exception ex)
{
}
}
UPDATE
You can find a similar explanation/example of what you are doing at:
http://www.dotnetperls.com/excel
Marshal.ReleaseComObject(book); // do this after the close
Also, there is a good discussion on cleaning up Excel/COM ...
How To Properly Clean Up Excel Interop Objects In c#

Related

How to find the row count of an Excel table using ASP.NET?

I am using the below mentioned code for finding the row count of an Excel table but it seems there is something wrong since I am not getting the desired output. Please provide some solution to it.
The code is as follows:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = null;
Excel.Workbook wb = null;
Excel.Worksheet worksheet = null;
int lastUsedRow = 0;
string srcFile = #"Path to your XLSX file";
xlApp = new Excel.ApplicationClass();
xlApp.Visible = false;
wb = xlApp.Workbooks.Open(srcFile,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
worksheet = (Excel.Worksheet)wb.Worksheets[1];
Excel.Range range
// Find the last real row
lastUsedRow = worksheet.Cells.Find("*",System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlPrevious,
false,System.Reflection.Missing.Value,System.Reflection.Missing.Value).Row;
xlApp.Workbooks.Close();
xlApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(wb);
Marshal.ReleaseComObject(xlApp);
You can try:
wb = xlApp.Workbooks.Open(srcFile,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
worksheet = (Excel.Worksheet)wb.Worksheets[1];
object[,] values = worksheet .UsedRange.Value2;
int rowCount = values.GetLength(0);
int colCount = values.GetLength(1);

Writing contents of two list to two different sheets in the same excel workbook

I am working on couple of C# list which need to be written to an excel workbook into two different sheets Sheet1 and Sheet2 but having no idea on how to deal with excel using interop I am using the following method
public void ExportListToExcel(List<String> listExport,string sheetName)
{
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[sheetName];
worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
for (int i = 1; i < listExport.Count + 1; i++)
{
//int count = 1;
worksheet.Cells[i, 1] = listExport[i - 1];
//count++;
}
string fileDestination = #"C:\Atlas Applications\AxiomParser\axiom.xls";
if (File.Exists(fileDestination))
{
File.Delete(fileDestination);
}
workbook.SaveAs(fileDestination, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
Process.Start(fileDestination);
app.Quit();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
ExportListToExcel(listMultiRowThreeWay,"Sheet1");
ExportListToExcel(listMultiRowButterFly, "Sheet2");
I am calling the above method twice with two sheet names in the method but it give me an invalid index error when executing the method for the second time
**Is there a better way to do it?**

com exception HRESULT: 0x800A03EC

I write a c# program for copy sheet. I got the exception error(0x800A03EC) when I call WorkSheet.Copy method until 105 times.
This is my snippet code: using Microsoft.Office.Interop.Excel;
private void CreateSheet(string dst_fileName)
{
object cell1 = "A2";
ApplicationClass app = null;
Workbook book = null;
Worksheet sheet = null;
Worksheet sheet_to_copy = null;
int i=0;
try
{
app = new ApplicationClass();
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
book = app.Workbooks.Open(dst_fileName, 0, false, 5, "", "", true,
XlPlatform.xlWindows,
"\t", false, false, 0, true, 1, 0);
// Reference to the worksheet
sheet_to_copy = (Worksheet)book.Worksheets[1];
for(;i<listViewPrg.Items.Count;i++)
{
sheet = (Worksheet)book.Worksheets[book.Worksheets.Count];
// Copy the worksheet to the end of the worksheets
sheet_to_copy.Copy(Missing.Value, sheet);
sheet.Name = "NewSheet(" + book.Worksheets.Count + ")";
}
book.SaveAs(dst_fileName, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
QuitExcel(app);
}
}
I can't found any solution about this. Could someone give me a hint to solve this problem?
Thank you so much.
Possibly you have some corrupted Excel registry entries or so?
Why don't you try to use an open source reader of excel files and do everything using them? The speed would skyrocket and i guarantee you would not get these errors!

How to read data from Excel file in C#?

I create an Excel file from c# with data validation-it seem like combo with chosen possibility
string mList1 = "=ProductCode";
oRng = oSheet.get_Range("H8", "H9");
oRng.Name = "ProductCode";
int t = dt.Rows.Count + 2;
string st = "F" + t;
oRng = oSheet.get_Range("F2", st);
oRng.Validation.Add(XlDVType.xlValidateList,
XlDVAlertStyle.xlValidAlertStop,
Missing.Value, mList1, Missing.Value);
Now I want to read the Excel file and also the chosen item from the combo. I have successfully read all the data but the data validation.
Read the data-
Microsoft.Office.Interop.Excel.Application ExcelObj = null;
ExcelObj = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open("C:\\Documents and Settings\\rachelg\\My Documents\\xxx.xls"
,Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
for(int x = 1; x <= 5; x++)
{
string sd = ((Microsoft.Office.Interop.Excel.Range)worksheet.Cells[x, 1]).Text.ToString();
System.Console.WriteLine(sd);//this one column
}
in different column I have the data validation but I don't know to access into it.
That seems a bit much for what is largely a simple operation.
Whilst not answering your question directly, this post I made a while back might help: accessing data record from Excel in VB.NET.

Searching a collection of excel sheets w/C#

I'm trying to get C# to examine whatever workbook the user has selected and find any sheets which would
contain stock data. Concretely this would mean looking at a range of cells (say r<6, c<10) for "Close", "close" or
"CLOSE".
The following code shows the point at which the user has selected an .xls file.
I'm not sure how to loop through the sheets in the workbook to look for the desired text.
I'm assuming it involves creating a collection of sheets and assigning it to those in the
current workbook, but my attempts so far haven't worked.
private void button1_Click(object sender, System.EventArgs e)
{
try
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Excel Files (*.xls)|*.XLS";
if (dlg.ShowDialog() == DialogResult.OK)
{
// MessageBox.Show(dlg.FileName, "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
Excel.Application xlApp = new Excel.ApplicationClass();
xlApp.Visible = true;
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(dlg.FileName,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
}
}
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");
}
}
Thanks for any ideas.
Jeff
Always take extra care to clean up when using the Interop libraries. Otherwise, you're likely to end up with a couple dozen EXCEL.EXE processes running in the background while you debug (or when a user hits an error).
private static bool IsStockDataWorkbook(string fileName)
{
Excel.Application application = null;
Excel.Workbook workbook = null;
try
{
application = new Excel.ApplicationClass();
application.Visible = true;
workbook = application.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
foreach (Excel.Worksheet sheet in workbook.Worksheets)
{
if (IsStockWorksheet(sheet))
{
return true;
}
}
return false;
}
finally
{
if (workbook != null)
{
workbook.Close(false, Missing.Value, Missing.Value);
}
if (application != null)
{
application.Quit();
}
}
}
private static bool IsStockWorksheet(Excel.Worksheet workSheet)
{
Excel.Range testRange = workSheet.get_Range("C10", Missing.Value);
string value = testRange.get_Value(Missing.Value).ToString();
return value.Equals("close", StringComparison.InvariantCultureIgnoreCase);
}
You'll need to assign objSheets to something, most likely:
Excel.Sheets objSheets = xlWorkbook.Sheets;
Your foreach statement should look more like this (with no prior declaration of the ws variable):
foreach(Excel.Worksheet ws in objSheets)
{
rng = ws.get_Range(ws.Cells[1,1], ws.Cells[5,9]);
}
Obviously, you'll want to do something more substantial in that loop.
This is an easy one :) use the sheets collection in the workbook object.
Workbooks workbooks = xlApp.Workbooks;
foreach(Workbook wb in workbooks)
{
Worksheets worksheets = wb.Worksheets;
foreach(Worksheet ws in worksheets)
{
Range range = ws.get_Range(ws.Cells[1,1], ws.Cells[5,9]);
Range match = range.Find("close", ws.Cells[1,1],
xlFindLookIn.xlValues, xlLookAt.xlPart,
xlSearchOrder.xlByColumns, xlSearchDirection.xlNext,
false, false, false); //that first false means ignore case
// do something with your match here
// this will only return the first match; to return all
// you'll need to run the match in a while loop
}
}

Categories

Resources