Change Code From Microsoft Interop To EPPlus - c#

I have created a set of code to export images from my Image folder into Excel using Microsoft Interop, now I want to change my codes from Microsoft Interop to EPPlus.
Can someone help me with this?
This is my codes:
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
string[] filesindirectory = Directory.GetFiles(Server.MapPath("~/Image"));
int count = 0;
foreach (string img in filesindirectory)
{
count++;
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
worksheet.Name = "Title- " + count;
TEST_IMAGE.ImageUrl = "Image/" + Path.GetFileName(img);
TEST_IMAGE.ImageUrl = this.GetAbsoluteUrl(TEST_IMAGE.ImageUrl);
worksheet.Shapes.AddPicture(TEST_IMAGE.ImageUrl, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 300);
}
workbook.Worksheets["Sheet1"].Delete();
workbook.Worksheets["Sheet2"].Delete();
workbook.Worksheets["Sheet3"].Delete();
workbook.SaveAs(#"C:\Users\user\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Quit();
Thanks.

To read an image into excel via epplus you can use this as an example (it will also show you how to setup a new workbook from scratch):
Weird behavior when setting a row's height on EPPlus
To delete a worksheet you can do that like this:
using (var pack = new ExcelPackage(existingFile))
{
var ws = pack.Workbook.Worksheets.Add("sheet1");
pack.Workbook.Worksheets.Delete(ws);
...
}
But if you are just trying to clean out the default sheets created by excel when you create a new file you DONT need to do that with EPPlus - by default there are no sheet when creating a new package (i.e. workbook). It is up to the programmer to add sheets and it will throw an error if there is not at least one.

Related

Close all open excel files except one

Good day to all.
I am trying to merge all the sheets of multiple excel files into one excel file. I have successfully did it using below code:
string folder = textBox1.Text;
string[] xlsxfiles = Directory.GetFiles(folder, "*.xlsx");
Excel.Application app = new Excel.Application();
app.Visible = true;
Excel.Workbook finalWB = app.Workbooks.Add("");
Excel.Workbook tempWB = app.Workbooks.Add(xlsxfiles);
for (int i = 2; i <= app.Workbooks.Count; i++)
{
for (int j = 1; j <= app.Workbooks[i].Worksheets.Count; j++)
{
Excel.Worksheet ws = app.Workbooks[i].Worksheets[j];
ws.Copy(app.Workbooks[1].Worksheets[1]);
}
}
However, the workbooks "tempWB" are still open and some of them got their filenames "1" added at the end (e.g.Book1.xlsx becomes Book11.xlsx).
I've already tried:
tempWB.Close();
but it is not closing the ones with "1" added to their filenames.
Is there a code that I can use to close all open excel files except one (finalWB in my code)?
Thank you in advanced for the ususal help.
I think app.Workbooks.Close(); needs to be called at the end to close all the open workbooks is there are any.
I have successfully closed all excel sheets by Saving As first the active workbook then run
app.Workbook.Close()
my code looks like below
finalWB.SaveAs(excelReportSaveas, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.Workbooks.Close();
Thank you Gowri for the reply.

How to Overwrite existing Excel file by adding new sheet with Excel Interop - C#

My program, every hour, does some math calculations and saves these result into excel. When it first run(lets say 08:00 AM) it creates a excel workbook and one sheet namely "Sheet1". It saves excel and releases the COM objects. so far everything is fine.
My problem begins with second run (09:00 AM). when it tries to save new results, it overwrites existing excel file (This is OK, the way i want it) but it overwrites Sheet1 which was created in 08:00 AM. I want it to save new result in Sheet2.
In third run, i want it to save result in Sheet3
In fourth run, i want it to save result in Sheet4. so on so forth..
How can i change my code to do like above ?
thanks in advance..
My Code:
using excelApp = Microsoft.Office.Interop.Excel;
public static void Main(string[] arg)
{
while (true)
{
writeToExcel();
int wait = 3600 * 1000;
System.Threading.Thread.Sleep(Convert.ToInt32(wait));
}
}
public static void writeToExcel()
{
excelApp.Application excl = new Microsoft.Office.Interop.Excel.Application();
excl.Visible = true;
//MATH CALCULATIONS......
excelApp.Workbook wb = excl.Workbooks.Add(excelApp.XlWBATemplate.xlWBATWorksheet);
excelApp.Worksheet ws1 = (excelApp.Worksheet)wb.Worksheets[1];
excelApp.Worksheet ws2 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws3 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws4 = (excelApp.Worksheet)wb.Sheets.Add();
excelApp.Worksheet ws5 = (excelApp.Worksheet)wb.Sheets.Add();
excl.DisplayAlerts = false;
string fileName = string.Format(#"{0}\Data_" + DateTime.Now.Month + "-" DateTime.Now.Day + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
workSheet.SaveAs(fileName);
Console.WriteLine("Excel Saved Successfully!!");
excl.Quit();
// Release COM objects
if (excl != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excl);
if (workSheet != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
excl = null;
workSheet = null;
GC.Collect();
}
You need to get the work book from the saved file. So at the beginning of your routine, you need a mechanism to determine if today's file already exists, if so, use the the following to get your Workbook.
Workbook WB = ExcelApp.Workbooks.Open(fileName, 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);
Hopefully this helps you see the error in your ways.

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?**

Find duplicate values in excel worksheet using conditional formatting programmatically

i need to find duplicate values in excel worksheet using conditional formating programmatically.
Tried this way, but in 6 line of code i've got COM exception
cannot cast to Excel.FormatCondition
Here's my code
Excel.Workbook xlWB = Application.ActiveWorkbook;
Excel.Worksheet xlWS = xlWB.ActiveSheet;
xlWS.Range["B2:B9"].Select();
Excel.Range xlS = Application.Selection;
xlS.FormatConditions.AddUniqueValues();
Excel.FormatCondition xlFC =
(Excel.FormatCondition)xlS.FormatConditions[xlS.FormatConditions.Count];
xlFC.SetFirstPriority();
Excel.FormatCondition xlFC1 = (Excel.FormatCondition)xlS.FormatConditions[1];
xlFC1.Interior.Pattern = Excel.XlPattern.xlPatternAutomatic;
xlFC1.Interior.TintAndShade = 0;
xlFC1.Interior.Color = ColorTranslator.FromOle(13551615);
Take a look at it MSDN Link
or you could possibly use something like this
Excel.Range usedRange = Worksheet.UsedRange;
usedRange.Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
FormatCondition format = (FormatCondition)(Worksheet.get_Range("A1:D13",
Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression,
XlFormatConditionOperator.xlEqual,
"=$A1=$D1", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing));
format.Font.Bold = true;
format.Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);//Duplicate values
Hope this helps ..it worked for me

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.

Categories

Resources