Error while generating excel from C# - c#

I have simple code for generating Excel which loops and produces excel sheet.
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value,Missing.Value,
6, Missing.Value);
for (int j = 0; j < 7; j++)
{
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName.ToString();//Sheetname has a Name
}
Now the problem is When we run this code everything works fine. But sometimes what happens is, at the client side one of the sheet name is not generated it skips. So our solution to them is to try generating the sheet again and then it works fine,
So my question is why does the code skip the sheetName (sometimes), although there is no problem in the code. Does it have to do anything with clients other running processes?

Try this:
Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;
XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
// here you get the first ws, index 1
Ws = (Excel.Worksheet)workbook.Worksheets[1];
workbook.Worksheets.Add(Missing.Value, Missing.Value,
6, Missing.Value);
var SheetName = "sheet_";
// here you should start from 1 (not from 0) and include 7 in the loop count
for (int j = 1; j <= 7; j++)
{
// make sure that the ws name is unique
SheetName=String.Format("sheet_{0}",j);
Ws = (Excel.Worksheet)workbook.Worksheets[j];
Ws.Activate();
Ws.Name = SheetName;// this is already a string
}
XlApp.Quit();

Related

C# Open new Excel Workbook and Add Data

From a console application using C# I am trying to open a new Excel workbook and add data to it. I can open a new workbook fine, but I am running into issues adding data to the workbook because my range object is null, and I can't seem to hook into the excel workbook that was just opened. I tried a variation of ActiveWorkbook, Sheets[1] and a couple of others and I can't seem to figure it out
using Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Application xl = null;
_Workbook wb = null;
// Option 1
xl = new Application();
xl.Visible = true;
wb = (_Workbook)(xl.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet sheet = xl.ActiveWorkbook.ActiveSheet;
Range cell = sheet.Cells[1, 1];
//ERROR on cell.Value("Test");
cell.Value("Test");
}
}
}
This code may be help you.
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Exported from gridview";
// storing header part in Excel
for (int i = 1; i < DGView.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGView.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < DGView.Rows.Count - 1; i++)
{
for (int j = 0; j < DGView.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = DGView.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
}
}
I used this code in my work for saving datagridview as excel sheet and it has been worked well.

Export SQL Data to an EXISTING Excel File (Specify Sheet)

The following code exports data to a excel file. It creates the file and creates a new sheet.
StringBuilder query = new StringBuilder();
query.Append("SELECT * from dbo.PastAdjs");
SQL.DataTable dtClients = new SQL.DataTable();
using (SqlConnection cn = new SqlConnection(conStr))
{
using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
{
da.Fill(dtClients);
progressBar1.Value = 20;
textBox1.Text = "20%";
}
//Create Excel workbook for export
Excel.Application oXL;
Excel._Workbook workbook;
Excel._Worksheet oSheet;
oXL = new Excel.Application();
oXL.Visible = false;
workbook = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)workbook.ActiveSheet;
Excel.Worksheet newWorksheet;
int sheetamt = 4;
for (int t = 1; t < sheetamt + 1; t++)
{
newWorksheet = (Excel.Worksheet)oXL.Worksheets.Add();
}
int count = workbook.Worksheets.Count;
Excel.Worksheet addedSheet = workbook.Worksheets.Add(Type.Missing,
workbook.Worksheets[count], Type.Missing, Type.Missing);
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = null;
worksheet1 = workbook.Sheets[1];
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Worksheet)worksheet1;
worksheet1.Name = "PastAdjs";
DataColumnCollection dcCollection = dtClients.Columns;
for (int i = 1; i < dtClients.Rows.Count + 1; i++)
{
for (int j = 1; j < dtClients.Columns.Count + 1; j++)
{
if (i == 1)
worksheet1.Cells[i, j] = dcCollection[j - 1].ToString();
else
worksheet1.Cells[i, j] = dtClients.Rows[i - 1][j - 1].ToString();
}
}
oXL.ActiveWorkbook.SaveCopyAs(filename);
oXL.ActiveWorkbook.Saved = true;
oXL.Quit();
How can I modify this to save to an existing worksheet in an existing excel file?

Excel worksheet won't delete [C#, WPF, VS 2010]

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
object misValue = System.Reflection.Missing.Value;
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Open(System.IO.Directory.GetCurrentDirectory() + #"\Report.xlsx");
// Get current worksheet and clear it
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = workbook.Worksheets[1];
Microsoft.Office.Interop.Excel._Worksheet worksheet2 = workbook.Worksheets[2];
app.DisplayAlerts = false;
worksheet1.Delete();
worksheet2.Delete();
app.DisplayAlerts = true;
//app.Worksheets[1].Delete();
//app.Worksheets[2].Delete();
workbook.Save();
Microsoft.Office.Interop.Excel._Worksheet worksheet = (Excel.Worksheet)app.Worksheets.Add(); ;
// storing header part in Excel
for (int i = 1; i < mydatatable.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = mydatatable.Columns[i - 1].ColumnName.ToString();
}
// storing Each row and column value to excel sheet
for (int i = 0; i < mydatatable.Rows.Count; i++)
{
for (int j = 0; j < mydatatable.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = mydatatable.Rows[i][j].ToString();
}
worksheet.Columns.AutoFit();
}
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = worksheet.get_Range("C1", "E20");
chartPage.SetSourceData(chartRange);
chartPage.ChartType = Excel.XlChartType.xlColumnClustered;
chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet,"Chart");
workbook.Save();
workbook.Close(misValue);
Marshal.ReleaseComObject(worksheet);
app.Quit();
It creates the new worksheet perfectly, but doesn't delete the old one first. I even have two codes to delete it and it doesn't. I have more than one sheet in the app.
EDIT: I just noticed that the first time I run the code it deletes the given sheets, but if I run it a second time (etc) it won't delete them anymore and gives me error, because aparently EXCEL proccess is still open in the background for some reason, altough I use "app.Quit()". Please help!
One of the problems could be that you have one worksheet when you're trying to delete it. Make sure that you're not deleting last worksheet or it won't work. So, create new one, then delete old one; not the other way around.
EDIT:
Try this code:
app.DisplayAlerts = false;
worksheetdel.Delete();
app.DisplayAlerts = true;
Source: https://stackoverflow.com/a/678795/2006048

c# excel how to change a color of a particular row

I want to ask you guys, how to change color of a row to red in Excel table if the cell 1 isn't null.
XX YY ZZ
-----------------
aa bb cc
aa1 bb1 cc1
aa2 cc2
aa3 bb3 cc3
aa4
Excel.Application xlApp;
Excel. Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
I'm very thankfull
Give this a shot, I have tested it and it works:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(#"C:\Test\Whatever.xlsx");
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range usedRange = worksheet.UsedRange;
Excel.Range rows = usedRange.Rows;
int count = 0;
foreach (Excel.Range row in rows)
{
if (count > 0)
{
Excel.Range firstCell = row.Cells[1];
string firstCellValue = firstCell.Value as String;
if (!string.IsNullOrEmpty(firstCellValue))
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
count++;
}
workbook.Save();
workbook.Close();
application.Quit();
Marshal.ReleaseComObject(application);
Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");
Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet);
xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"];
xlWorkSheetToExport.Range["A5:F5"].EntireRow.Interior.Color = System.Drawing.Color.Gray;

Prevent Excel from opening while creating excel file using interop

Hi all am creating a excel using Microsoft office interop.and it creates files successfully.But the problem is that when it creates a files it just opens excel adds the value in to excel and saves it in the specified name.Any accidental typing at that time results leads to a exception.Am creating nearly 75 files with many rows from database and hence takes time.During the processing am unable to do any task since it creates exception if its typed in the excel.Is there any way to run the process in background so that excel application does not open for each file creation.
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
Excel.Range oRange;
// Start Excel and get Application object.
oXL = new Excel.Application();
// Set some properties
oXL.Visible = true;
oXL.DisplayAlerts = false;
// Get a new workbook.
oWB = oXL.Workbooks.Add(Missing.Value);
// Get the active sheet
oSheet = (Excel.Worksheet)oWB.ActiveSheet;
oSheet.Name = "Sales";
// Process the DataTable
// BE SURE TO CHANGE THIS LINE TO USE *YOUR* DATATABLE
DataTable dt = dtt;
int rowCount = 1;
foreach (DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
// Add the header the first time through
if (rowCount == 2)
{
oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
// Resize the columns
//oRange = oSheet.get_Range(oSheet.Cells[1, 1],
// oSheet.Cells[rowCount, dt.Columns.Count]);
oRange = oSheet.Range[oSheet.Cells[1, 1], oSheet.Cells[rowCount, dt.Columns.Count]];
oRange.EntireColumn.AutoFit();
// Save the sheet and close
// oSheet = null;
oRange = null;
oWB.SaveAs("" + username + " .xls", Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
oWB.Close(Missing.Value, Missing.Value, Missing.Value);
oWB = null;
oXL.Quit();
// Clean up
// NOTE: When in release mode, this does the trick
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
By default Excel via Interop opens as Invisible.
It's your code that change the visibility of Excel.
Remove the line
oXL.Visible = true;
or set to false
oXL.Visible = false;
Try this...
// Start Excel and get Application object. oXL = new Excel.Application {Visible = false};
OR -
// Set some properties oXL.Visible = false;

Categories

Resources