Excel Interop Picture not displaying - c#

hopefully you guys can help me here. I have this excel interop picture code that seems to be only working on my end. The picture is in a folder in the mapped network drive. When I run the code and receive the excel file, the picture is on the file.
Microsoft.Office.Interop.Excel.Range picRange = xlWorkSheet.get_Range("A1:G1");
picRange.Merge(Type.Missing);
Microsoft.Office.Interop.Excel.Pictures p = xlWorkSheet.Pictures(misValue) as Microsoft.Office.Interop.Excel.Pictures;
Microsoft.Office.Interop.Excel.Picture pic = null;
pic = p.Insert(Server.MapPath("~/images/letter.gif"), misValue);
pic.Left = 87;
pic.Top = Convert.ToDouble(picRange.Top);
pic.Height = 80.25;
pic.Width = 320;
pic.Placement = Microsoft.Office.Interop.Excel.XlPlacement.xlFreeFloating;
However, if I run the code on a different computer, which also has access to that mapped network drive, it the excel file comes with an error on the image that says:
the linked image cannot be displayed. The file may have been moved
renamed or deleted
I've checked three times and made sure that the image file is the right name and the right place. But it only seems to work locally on my computer.
Is there a function in the excel interop library where I can create an instance of the image instead of linking to the image file? Any help will do.

Related

How to solve Excel opening Error Generated by EPPlus .Net library

I am generating several excel copies from a template (its really big).
For that First I am taking the template from a file location, then based on a loop for every iteration I am creating a new ExcelPackage(newFile,Template).
After that I am taking the exact ExcelWorksheet that I have to edit.
Then after editing I am Saving as the file as newFile. The time of opening the saved file Two problem is occurring:
If there is no Excel instance is running on the PC then the saved file is opening but with no data.
If the Excel instance is running then the saved file is opening with Warning message but working. "Problem with some content with Excel. Do you want us to recover?" and "Excel was able to recover some unreadable content "
string templateExcel = #"Location\template.xlsx";
FileInfo templateFile = new FileInfo(#"Location\newFile.xlsx");
using (FileStream templateExcelStream = File.OpenRead(templateExcel))
{
using (ExcelPackage copyExcel = new ExcelPackage(templateExcelStream))
{
ExcelWorksheet presentWorkSheet = copyExcel.Workbook.Worksheets["Name"];
presentWorkSheet.Cells[4, 2].Value = Value from condition;
copyExcel.SaveAs(templateFile);
}
}
Thanks all of you for your valuable time. I got the solution.
For me the issue was in the template itself as it contained invalid references to lookup tables. I found this in Formula -> Name Manager.
I suggest that you check the template if you face this issue.

Get and Save particular Excel file in same location using C#

I am using Asp.Net MVC application, Visual Studio 2013, SQL Server Data base
There is a particular location in my system's local drive i.e., c:/Files/Exim_Files/ , where a lot of excel(.xlsx) files are sitting.
I want to get the particular file from that location and save it programmatically (without Save pop up) in same location with same/different name. while saving the excel data should not be lost, file should be as it is, just I need to save/SaveAs it again.
How can I achieve this requirement?
Note that I am using Virtual Machine and inside Virtual Machine: Microsoft Office is not installed. So the code will have to work without Microsoft Office installation in the machine. I can only use Microsoft Office in my host machine.
Edit
In below code, I am using Aspose.Cells to save the Excel file from 1 location to another.
I am getting the particular File from sharedLocation in array "l_strFileUploadPath" and then checking, if the file that I am getting from user exists in shared location, then I want to save/SaveAs that
file into different location (defined in 'string str') along with entire data (say I want to import the data as well while Saving the Excel in different location).
The issue I am facing is that, the file that is getting saved in C: drive, is not saving the data which is present inside the Excel. It seems it is creating a new excel file in c: drive with same name (x-TECHNICAL_DIT_BUDV01_RV124_R01_2015_Test.xlsx) having 2 sheets.
1 is 'sheet 1' and another is 'Evaluation Warning' sheet.
How can I remove the 'Evaluation Warning' sheet and what is the method of saving the exact file (along with data) from shared drive to c: drive, as per my code.
This is the first time using Aspose.Cells to get and Save/SaveAs the file from 1 location to another.
protected void getFileAndSave()
{
string[] l_strFileUploadPath = Directory.GetFiles("//181.184.11.435/share//Temp/New folder");
foreach (var filename in l_strFileUploadPath)
{
string fileName = Path.GetFileName(filename);
string p_filename = "x-TECHNICAL_DIT_Test.xlsx"; //this is the file I am getting from user
if (fileName == p_filename)
{
//-- Using Aspose.Cells
Workbook wb = new Workbook();
Worksheet worksheet = wb.Worksheets["Sheet1"];
worksheet.Name = "Technical Data";
//Save workbook with export cell as true
OoxmlSaveOptions opts = new OoxmlSaveOptions();
opts.ExportCellName = true;
wb.Save(str + file, opts);
}
}
}
It seems for me that you just want to copy the file.
Take a look at File.Copy()
File.Copy(#"c:\excel.xsl", #"c:\other\excel.xsl");
EDIT for comment:
I think it will be hard to change app.xml metadata without just manually looking what changes are made there during save/saveAs and then trying to understand how to copy this behavior and change it programmatically inside that file.

How to embed images in Excel using C#?

I currently have a list of Products in a SQL database, and one of the fields is a blob field that contains an image of the Product, I store it and retreive it using a Byte[] array, and the image is taken from PNG format. Displaying the images on the website when a user views a Product is working correctly.
What the customer now wants though is an export of all the products to Excel, including the images to be displayed in each row for each product, lets say Column F.
I've not been finding any information online that seems to work - sample code always seems to have an error or reference things that I can't find, which makes me wonder if there's versioning issues. I'm currently using Visual Studio 2010 and Office 2010 to test this.
I've seen some samples showing how to take the image to Clipboard and paste it, but considering that this will be running on a web server and might have to handle 20 or so products at a time, I'm not sure clipboard would be a good idea for a webserver?
I'd prefer to be able to write it into the excel file directly from the Byte[] array as I'm pulling all the other product data.
Before I update the code on the website, I'm trying to test it locally using a simple Console program. Once I know I can get an image into Excel, I'll probably write a dll library I can reference on the aspx page.
var xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add();
Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets[1];
byte[] imgdata = File.ReadAllBytes("product.png");
//what do I enter here to insert the image into cell[1,1]
xlWorkBook.SaveAs("abc.xlsx");
xlWorkBook.Close(true);
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
The key is to use worksheet paste function instead of using AddPicture if you want to use byte data instead of files on hard disk:
Bitmap bmp;
using (var ms = new MemoryStream(imgdata))
{
bmp = new Bitmap(ms);
System.Windows.Forms.Clipboard.SetDataObject(bmp, False);
var rng = xlWorkSheet.Range("A1");
xlWorkSheet.Paste(rng, bmp);
}

EPPlus Excel error when using AddPicture

I been trying to find the solution for this for so many hours i'm really tired, i hope someone can indicate me with i'm missing. I will try to be as clear as posible with all the possible information so there is no confusion.
I'm using EPPlus 3.1.3.0, Visual Studio 2010, C#, MVC.NET Framework 4.0 and MS Excel 2007
I'm just trying to do a simple thing: download an Excel file with a picture in it. Nothing else.
I have an action that opens an excel file, fills it with data and adds a picture which code looks like this:
public ActionResult FillExcelFile(string imagePath)
{
FileInfo template = new FileInfo([path_of_excel_file]);
ExcelPackage xls = new ExcelPackage(template);
ExcelWorksheet worksheet = xls.Workbook.Worksheets["Sheet1"];
worksheet.Cells[1, 1].Value = "data1";
worksheet.Cells[1, 2].Value = "data2";
worksheet.Cells[1, 3].Value = "data3";
/* ToDo: add picture */
return File(xls.GetAsByteArray(), "application/vnd.ms-excel", "excel.xlsx"));
}
At this moment everything works great! The file have the information and i can download and open it with no problem at all.
Now i will add the picture i want, i will change the ToDo part with the next code:
Image img = Image.FromFile(imagePath);
ExcelPicture pic = worksheet.Drawings.AddPicture("img", img);
pic.SetPosition(1, 1);
Run it, download it, open it aaand... error:
Excel found unreadable content in "excel.xlsx". Do you want to recover... blah blah blah
Of course i want to recover.
Files open aaand... is empty and an error appear:
Replaced Part: /xl/worksheets/sheet1.xml part with XML error. Load error. Line...
From this moment till now i been adding different code:
Image img = Image.FromFile(imagePath);
ExcelPicture pic = worksheet.Drawings.AddPicture("img", img);
pic.SetPosition(1, 1);
pic.SetSize(100, 100);
And...
Bitmap img = new Bitmap(Image.FromFile(imagePath));
ExcelPicture pic = worksheet.Drawings.AddPicture("img", img);
pic.SetPosition(1, 1);
And...
FileInfo img = new FileInfo(imagePath);
ExcelPicture pic = worksheet.Drawings.AddPicture("img", img);
pic.SetPosition(1, 1);
With the last one there as exception:
: System.ArgumentException: Part URI is not valid per rules defined in the Open Packaging Conventions specification
And many many many more like open the image with a stream, adding the setSize because someone said some kind of problem if you don't define it, define my own URI, save the file in the server then download it, etc.
I really appreciate any help that you can give me, really. I don't known what else to check. If you require more information be free to ask.
i found the problem... or kind of. Thanks to #Chris to guide me in this one and to #Ernie for the sugestion.
The problem is the template file that i was trying to fill has something inside that doesn't work fine when i try to add an image. #Chris says "you already have a drawing part in the template and EPPlus is creating some sort of conflict". I don't know what could that be.
So i create a new template from scratch (the template i was using was done by someone else) and everything worked like charm.
Steps that i performed:
I created a new file with using EPPlus and download it and it worked.
I created a new empty template and add the image with EPPlus and it worked.
I created a new template with all the stuff i needed in it and it worked.
I hope this help someone else if they have a similar problem.
I had the same problem. With prueba prueba's answer I analysed my original template and found this: If the table formatting feature (see screenshot) is used then AddPicture causes the XML errors. My solution was to remove the table formatting.
I've had the same issue and noticed that when you add a background-picture before adding the picture the file gets corrupted. If you add the background picture afterwards it works fine.
osheet.BackgroundImage.Image = My.Resources.anyimage
I found the same problem. I'm using the version 4.1.0.0.
I try to use this code:
Bitmap arquivoLogotipo = new Bitmap(#"C:\xxxxxx.jpg");
ExcelPicture logotipoExcel = principal.Drawings.AddPicture("logotipo", arquivoLogotipo);
logotipoExcel.SetPosition(50, 250);
I try this too:
FileInfo logotipoEndereco = new FileInfo("C\okokoko.jpg");
var logotipo = principal.Drawings.AddPicture("logotipo", logotipoEndereco);
logotipo.SetPosition(50, 250);
In my case, I just have a blank sheet. My cod just insert a name of a project and one image.I really don't know what is happening.
Thanks :D!

c# add a picture to excel from resources

I'm currently doing the below to add an image to an excel file I'm creating via "interop"
private Excel.Workbook _xlWorkBook;
_xlWorkSheet.Shapes.AddPicture(appPath + #"\ImageFile.png", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 5, 5, 60, 60);
I have a couple of questions if I may.
How can I access the picture once it's added - e.g. to draw a border on it.
Doing the above for my app means that I have to distribute the image file as well so I thought I would put it in the application resources. How do I add the image from the resources to the excel file? Again once added, how do I access it to add border etc?
_xlWorkSheet.Shapes.AddPicture(Properties.Resources.ImageFile); //dosn't work
Many thanks
1.) I believe you can access the picture by using
// after adding the picture
Picture pic = (Picture) ActiveSheet.Pictures(ActiveSheet.Pictures.Count - 1);
pic.Border.LineStyle = XlLineStyle.xlContinuous;
pic.Border.Weight = XlBorderWeight.xlMedium;
Or
// add the picture using Pictures.Insert
// this should return a Picture cast-able object
Picture pic = (Picture) ActiveSheet.Pictures.Insert(FileName);
// etc...
2.) The simplest way would be to pull the file from resources write it to a temp file, add it into excel and then remove the temp file.
This code is very much untested. Excel interop is a head-ache.
Sorry or the archeology.
For the second question, adding a picture from a ressource, I may have found a solution using the clipboard:
System.Drawing.Bitmap pic = Properties.Resources.my_ressource;
System.Windows.Forms.Clipboard.SetImage(pic);
Range position = (Range)myWorksheet.Cells[Y, X];
myWorksheet.Paste(position); //copy the clipboard to the given position
RE: 2. I did this:
S = Shapes.AddPicture(filename,MsoTriState.msoFalse,MsoTriState.msoTrue,0,0,50,50);
S.Name = "Picture";
S.Placement = XlPlacement.xlMoveAndSize;

Categories