Insert an image into excel cells using c# - c#

I am Generating a Excel sheet from datatable dyanamically. I am able to add text into different cells as i needed. But i do not have any idea about how to add picture into a specified range..
Excel.Application oApp = new Excel.Application();
oApp.Application.Workbooks.Add(Type.Missing);
oApp.Range["B2", "C4"].Merge(Type.Missing);
Here i want to add picture..
I am trying like
System.Drawing.Image imgg = System.Drawing.Image.FromFile("c:\\D.jpg");
Now how could i add/copy my imgg into this range?? e.g.
App.Range["B2", "C4"]

You can get benefited with the following
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//add some text
xlWorkSheet.Cells[1, 1] = "Text1";
xlWorkSheet.Cells[2, 1] = "Text2";
xlWorkSheet.Shapes.AddPicture("C:\\sample.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45);
xlWorkBook.SaveAs("MyExcelFile.xls", Excel.XlFileFormat.xlWorkbookNormal, 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);
MessageBox.Show ("File created !");
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}

Have you tried giving position with excelpicture?
var picture = worksheet.Drawings.AddPicture("image_name", imgg);
picture.SetPosition(int row,int rowoffsetpixels,int column,int coloumoffsetpixels);//position for the image

You can add an image to your Excel spreadsheet quite easily (this assumes that you are using Microsoft.Office.Interop.Excel assembly reference, in C#) like this:
private Worksheet _xlSheet;
private Image _platypusLogo;
. . .
private void AddImage()
{
Clipboard.SetDataObject(_platypusLogo, true);
var cellRngImg = (Range)_xlSheet.Cells[IMAGE_ROW, IMAGE_COLUMN];
_xlSheet.Paste(cellRngImg, _platypusLogo);
}
Note that "IMAGE_ROW" and "IMAGE_COLUMN" are int constants or you can just use hard-coded ints, if you want to fly in the face of Steve McConnell's advice in Code Complete about constantifying all numbers other than sometimes 0 and 1
An image needs to be assigned to _platypusLogo. If you are using a C# utility app to dynamically generate the Excel spreadsheet, you could add a PictureBox control to a form, and then assign an image to it via its Image property (the control is named, by default, pictureBox1), and then assign it to the spreadsheet this way:
_platypusLogo = pictureBox1.Image;
Of course, you can assign to _platypusLogo directly/exclusively in code, too, if you prefer.

Related

Can we develop a .exe file, in c# for macros to set up excel file in new machine which does not contains any macros earlier

I need to develop an .exe file whenever we clicks on it should copy Personal.XLSB and Excel customization from one folder to XLSTART folder in perticular machine(i have done with this).And check the checkbox of developer tab and import of Excel customization through c# code. is it possible?help please.
Done with the files copy from one place to another.Now i have to do is import of Excel customization file and check checkbox of Developers tab in excel option. is this possible through c# code?
Well, an EXE file is created as long as you build the project. So...BUILD->Batch Build And activate the "build" checkbox in the release configuration. When you click the build button, the exe with some dependencies will be generated. You can find this file on the debug folder of you project.
C:\Users\username\Documents\Visual Studio 2012\Projects\ProjectName\bin\Debug
Here is the code.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
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:\\csharp-Excel.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");
}
}
}
Also, see the link below.
http://csharp.net-informations.com/excel/csharp-create-excel.htm

how to solve Object reference not set to an instance of an object error [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I am making a Program to convert a csv( common selected value file) file into xls(microsoft excel file) file
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConversionToXLSFile
{
public partial class Converter : System.Web.UI.Page
{
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel.Application xlApp;
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);
protected void Page_Load(object sender, EventArgs e)
{
//List<string> row = new List<string>();
string fullPath = #"D:\Work\Sep-14\ConversionToXLSFile\ConversionToXLSFile\File\diff_16122014095440.csv";
string[] fileRows = File.ReadAllLines(fullPath, Encoding.UTF8);
foreach (string rows in fileRows)
{
var columns = rows.Split(';');
for (int j = 0; j < fileRows.Length; j++)
{
for (int i = 0; i < columns.Length; i++)
{
List<string> elements = new List<string>();
foreach (string col in columns)
{
elements.Add(col);
xlWorkSheet.Cells[j, i] = col;
}
}
}
}
xlWorkBook.SaveAs("d:\\csharp-Excel.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);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
private void Add(dynamic dynamic)
{
throw new NotImplementedException();
}
}
}
As far as I can see, you've commented out the code where you assign the variables xlApp, xlWorkBook and xlWorkSheet...
//Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
//xlWorkBook = xlApp.Workbooks.Add(misValue);
//xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Take the // out of each line and you won't get null reference exceptions when you try to use them.

The Time value is not reflecting correctly in my excel worksheet

I managed to create an Excel file and tried to update the current system timings into first cell of the worksheet. But when the file is created, I get wrong values for timings. I want the current system time but it is displaying 12:00:00 However date is being displayed correctly.
I am using Microsoft Excel 12.0 Object Library. I need help to get the current system timings or need to reflect the timings as per the date time picker.
Here is my code:
namespace Test6attendance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");
xlWorkBook.SaveAs("D:\\login.xlscsharp-Excel.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("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;
MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
}
It is because of the following line:
xlWorkSheet.Cells[1, 1] = DateTime.Now.Date.ToString("MM/dd/ yyyy, hh:mm:ss tt");
DateTime.Now.Date will set the time property to Midnight. Use this Instead
xlWorkSheet.Cells[1, 1] = DateTime.Now.ToString("MM/dd/ yyyy, hh:mm:ss tt");
Here is the DateTime.Now Property, DateTime.Date Property

Copy data from datagrid to Excel and open the file without saving it

I'm working on VS 2003 C# WINFORM.
I want where I click the button, the datagrid (not datagridView) will be copied in the Excel file and it will be opened (with data of course) then the user will choose if he want to save it after the analyse or not.
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel files (*.xls)|*.xls|All files (*.*)|*.*" ;
sfd.FilterIndex = 1 ;
sfd.RestoreDirectory = true ;
sfd.Title = "Liste des différés";
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if(sfd.ShowDialog() == DialogResult.OK)
{
if(sfd.FileName.Length > 0)
{
string data = null;
int i = 0;
int j = 0;
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);
for (i = 0; i <= dsSelectionListeDiffere.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= dsSelectionListeDiffere.Tables[0].Columns.Count - 1; j++)
{
data = dsSelectionListeDiffere.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 1, j + 1] = data;
}
}
// Pass the full path to the SaveAs method
// string fullPathName = Path.Combine(folderName, "csharp.xls");
xlWorkBook.SaveAs(sfd.FileNames, 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);
}
}
}
catch(Exception ex )
{
MessageBox.Show(ex.Message);
}
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();
}
}

Excel worksheet change event is not firing

I have created excel workbook using .NET interop. The excel workbook is created successfully through my C# code. When the user makes any changes in the excel, I want to do some stuff. I have used the ExcelWorkSheet.Change event. But this event is not firing. Here is my code-
using Excel = Microsoft.Office.Interop.Excel;
public class xxx
{
static Excel.Application xlApp;
static Excel.Workbook xlWorkBook;
static Excel.Worksheet xlWorkSheet;
static Excel.Worksheet xlWorkSheet1;
static Excel.DocEvents_ChangeEventHandler EventDel_CellsChange;
public static void ExportToExcel()
{
xlApp = new Excel.ApplicationClass();
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
---------------- data is dumped to the excel here----------------
((Microsoft.Office.Interop.Excel._Worksheet)xlWorkSheet).Activate();
xlApp.EnableEvents = true;
EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler(Worksheet_Change);
xlWorkSheet.Change += EventDel_CellsChange;
xlWorkBook.SaveAs("D:\\Test.xlsx", Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlShared, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet1);
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=Test.xlsx;");
response.TransmitFile(("D:\\Test.xlsx");
response.Flush();
response.End();
}
public static void Worksheet_Change(Excel.Range Target)
{
try
{
xlApp.EnableEvents = false;
Excel.Range range = xlWorkSheet.get_Range("Y2");
range.Formula = "=A2";
}
catch (Exception ex)
{
}
finally
{
xlApp.EnableEvents = true;
}
}
}
No change is reflected in the Excel file when the user makes some changes.
Please help me out.
Thanks in advance
The Worksheet_Change event is not global - it only applies to that particular worksheet. In your code you wire up the event handler to the xlSheet1.Change event, then close the workbook and release all the Excel objects.
EDIT: I popped your code behind a Form and adapted it slightly. I could get the event to fire and the formula in cell Y2 is set. I'm not 100% sure of your circumstances, but try this code and then compare with your own. Hope it helps.
public partial class Form1 : Form
{
private static Excel.Application xlApp;
private static Excel.Workbook xlWorkBook;
private static Excel.Worksheet xlWorkSheet;
private static Excel.Worksheet xlWorkSheet1;
private static Excel.DocEvents_ChangeEventHandler EventDel_CellsChange;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
xlApp = new Excel.Application();
xlApp.Visible = true;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
//---------------- data is dumped to the excel here----------------
((Microsoft.Office.Interop.Excel._Worksheet)xlWorkSheet).Activate();
xlApp.EnableEvents = true;
EventDel_CellsChange = new Excel.DocEvents_ChangeEventHandler(Worksheet_Change);
xlWorkSheet.Change += EventDel_CellsChange;
}
public static void Worksheet_Change(Excel.Range Target)
{
try
{
xlApp.EnableEvents = false;
Excel.Range range = xlWorkSheet.get_Range("Y2");
range.Formula = "=A2";
}
catch (Exception ex)
{
}
finally
{
xlApp.EnableEvents = true;
}
}
}

Categories