get list of opened Excel documents in C#? - c#

Here i get Word document opened file list successfully..
try
{
Microsoft.Office.Interop.Word.Application WordObj;
WordObj = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
x = "";
for (int i = 0; i < WordObj.Windows.Count; i++)
{
object idx = i + 1;
Microsoft.Office.Interop.Word.Window WinObj = WordObj.Windows.get_Item(ref idx);
// doc_list.Add(WinObj.Document.FullName);
x = x + "," + WinObj.Document.FullName;
//x = WinObj.Document.FullName;
}
}
catch (Exception ex)
{
// No documents opened
}
As same as i wantt to get Excel files list...
try
{
Microsoft.Office.Interop.Excel.Application ExcelObj;
ExcelObj = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
//excel = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
x = "";
for (int i = 0; i < ExcelObj.Windows.Count; i++)
{
object idx = i + 1;
Microsoft.Office.Interop.Excel.Window WinObj = ExcelObj.Windows.get_Item(idx);
doc_list.Add(WinObj.Document.FullName);
//Here is the problem ,How can i get FullName of opened excel file
// x = x + "," + WinObj.Activate.
// x = WinObj.Document.FullName;
}
}
catch (Exception ex)
{
}
Excel file not getting..This Line..
In every word document getting fine..with WinObj.Document.Fullname but
In Excel x = x + "," + WinObj.Document.FullName; No Propertity for Excel File name Document...How Can i get File Full name as same as word..

I found this on stackoverflow
You can try it.
//Excel Application Object
Microsoft.Office.Interop.Excel.Application oExcelApp;
this.Activate ( );
//Get reference to Excel.Application from the ROT.
oExcelApp = ( Microsoft.Office.Interop.Excel.Application ) System.Runtime.InteropServices.Marshal.GetActiveObject ( "Excel.Application" );
//Display the name of the object.
MessageBox.Show ( oExcelApp.ActiveWorkbook.FullName );
//Release the reference.
oExcelApp = null;
I found this here
How to get the current open documents in Excel using C#?
and here
http://support2.microsoft.com/kb/316126

Related

c# - How to make excel auto calculate formula type cells

I have an excel file that has around 40 to 50 sheets of size 8mb and will be increasing may be 15 to 20mb and many are inter-linked with multiple formulas.
So basically if one cell values changes then it will affect multiple sheets because of function and vlookup's etc.
Now I am trying to manipulate the excel sheet dynamically using c#. But I see that the are not calculating instantly.
I tried using ExcelLibrary's Calculate function to do this.
Problems with ExcelLibrary are:
a. It is very very slow with Calculate, ExcelPackage(Open) and Save functions**(Makes it unusable)**.
b. Need to know all the dependent cell to trigger calculate on them(not preferring workbook or worksheet calculate(the debugger never comes to next line)) which is not efficient way to manage code in feature.
I believe the problem is because it works with ooxml and actually not directly with excel(not sure we can work with excel directly so that it will be like inserting data manually using code).
Note: Trying to test with Excel interop(hoping it will do the job because it opens excel file in background while manipulating.)
private void TestExcelWithSimultaneousReadOfTwoSheetsFromFile(string fileName)
{
try
{
int count = 0;
int rowIndex = 1702;
for (int rowCount = 0; rowCount < 3; rowCount++)
{
count = ReadCountFromProdReport(fileName);
WriteRowToProd(fileName, rowIndex + rowCount);
count = ReadCountFromProdReport(fileName);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void WriteRowToProd(string fileName, int rowIndex)
{
try
{
string logDirectory = System.Configuration.ConfigurationManager.AppSettings["LogDirectory"].ToString().Trim();
string filePath = logDirectory + fileName + ConfigurationManager.AppSettings["ExcelSaveFileExtension"].ToString().Trim();
using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath)))
{
foreach (ExcelWorksheet workSheet in excelPackage.Workbook.Worksheets)
{
if (workSheet.Name.Trim() == "Sample")
{
workSheet.Cells["C" + rowIndex].Value = "15.05.2017";
workSheet.Cells["D" + rowIndex].Value = 21701503;
workSheet.Cells["E" + rowIndex].Value = "21701503109W";
workSheet.Cells["F" + rowIndex].Value = 304;
workSheet.Cells["G" + rowIndex].Value = 200;
workSheet.Cells["H" + rowIndex].Value = 1520;
workSheet.Cells["I" + rowIndex].Value = 11350;
workSheet.Cells["J" + rowIndex].Formula = "=7.85*G1701*H1701*I1701/1000000000";
workSheet.Cells["K" + rowIndex].Value = 27.080;
excelPackage.Save();
break;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
private int ReadCountFromProdReport(string fileName)
{
try
{
string logDirectory = System.Configuration.ConfigurationManager.AppSettings["LogDirectory"].ToString().Trim();
string filePath = logDirectory + fileName + ConfigurationManager.AppSettings["ExcelSaveFileExtension"].ToString().Trim();
using (ExcelPackage excelPackage = new ExcelPackage(new FileInfo(filePath)))
{
object count = null;
foreach (ExcelWorksheet workSheet in excelPackage.Workbook.Worksheets)
{
if (workSheet.Name.Trim() == "Report")
{
count = workSheet.Cells["E23"].Value;
break;
}
}
return Convert.ToInt32(count);
}
}
catch (Exception ex)
{
throw ex;
}
}

Outlook new email to Excel row

I want to create a C# Console app (or a service - not sure how to develop a service yet) that:
1) Knows when a new email is received in Inbox>LOTALogs folder. This email is sent by a mobile application and includes an attachment and some issues that the customer experienced.
2) Takes the new email content, which is comma-separated, parses and appends the content into an Excel worksheet that already has the columns set up.
I managed to create:
1) The parser:
public static string[] emailContentsArray()
{
string content = "Username = Customer1,User ID = 362592,Unit ID = 805618,Date = Mar 12, 2017,Device = Android LGE LG-H990,OS version = 7.0 (API 24),App version = 1.0.0.56,Description = some description,Message = some message";
string[] contentArray = content.Split(',');
// Case where date format includes another comma
if (contentArray.Length > 10)
{
// Parsing headers
contentArray[0] = contentArray[0].Substring(11);
contentArray[1] = contentArray[1].Substring(10);
contentArray[2] = contentArray[2].Substring(10);
contentArray[3] = contentArray[3].Substring(7) + ", " + contentArray[4].Substring(1);
contentArray[4] = contentArray[5].Substring(9);
contentArray[5] = contentArray[6].Substring(13);
contentArray[6] = contentArray[7].Substring(14);
contentArray[7] = contentArray[8].Substring(14);
contentArray[8] = contentArray[9].Substring(10);
contentArray[9] = null;
for (int i = 0; i < contentArray.Length; i++)
{
Console.Write(contentArray[i] + ",");
}
}
//else
//{
//}
return contentArray;
}
2) Accessed the folder and counted the number of items:
public static string[] emailContent()
{
string[] content = null;
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook.NameSpace ns = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
Microsoft.Office.Interop.Outlook.MAPIFolder logFolder = null;
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
logFolder = app.ActiveExplorer().CurrentFolder = inboxFolder.Folders["LOTALogs"];
int itemCount = logFolder.Items.Count;
Console.WriteLine("\n\nFolder Name: {0}, Num Items: {1}\n", logFolder.Name, itemCount);
return content;
}
3) Opened and printed the contents of the spreadsheet:
Excel.Application xlApp = new Excel.Application();
string path = "C:\\SomeUser\\BugReports";
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(#path);
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
for (int i = 1; i <= xlRange.Row + xlRange.Rows.Count - 1; i++)
{
for (int j = 1; j <= xlRange.Column + xlRange.Columns.Count - 1; j++)
{
if (j == 1)
Console.Write("\r\n");
if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");
}
}
xlWorkbook.Save();
xlWorkbook.Close();
xlApp.Quit();
Console.ReadLine();
I am a little lost now :)
I still need to:
1) Create an event listener (I think that's what it's called) so I can tell the email body parser to go fetch the email contents.
2) Extract the email body from the email.
Got this using
Console.WriteLine(logFolder.Items[1].Body);
3) Take the email content and append it to the spreadsheet.
4) Should I create this as a Windows Service?
PS - I am not a developer, just fiddling around with code and trying to be as efficient as possible. I don't want to fill this spreadsheet out manually when there's a technological solution in sight. Please comment if you have any suggestions on being more efficient with the code and model it differently.
Looks solid to me. I'd refrain from the service, but it greatly depends on your users. Unless your customer really wants to be "blind" from the whole process, it adds a lot of unwarranted complications.
As for appending to the spreadsheet...
int lastRow = xlWorksheet.UsedRange.Rows;
Excel.Range xlRange = xlWorksheet.Cells[lastRow + 1, 1];
xlRange.Value = stuffFromInbox;
If you're only adding the one item to the spreadsheet, this will work fine. For mass read/write operations with the spreadsheet (like your "Opened and printed the contents of the spreadsheet"), it would be much more efficient to read the Value or Value2 of the entire Range into a object[,]. Then iterate through the local array.

Export Linq query result to excel EPPLUS

I have developed a program to get the Linq query and write it to excel file using EPPLUS (the below code) but it is slow because it is filling the file line by line. is there anyway to fill the excel file all at once? to export all the query at once to excel file?
fnctnData is the query result
Thanks for the help
public Boolean GenerateExcel(IEnumerable<ReportData> fnctnData,string fileName,ReportFilTer smf)
{
Boolean ret=false;
try
{
string temp = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
DirectoryInfo di = new DirectoryInfo(temp);
string templateFile = Path.Combine(di.Parent.FullName, #"templates\Report.xlsx");
FileInfo itemplateFile = new FileInfo(templateFile);
FileInfo ReportFile = new FileInfo(fileName);
using (ExcelPackage package = new ExcelPackage(ReportFile,itemplateFile))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
int i = 5;
foreach (var item in fnctnData)
{
worksheet.Cells["A" + i].Value = item.a;
worksheet.Cells["B" + i].Value = item.c;
worksheet.Cells["C" + i].Value = item.d;
worksheet.Cells["D" + i].Value = string.Format("{0:dd/MM/yyyy hh:mm:ss}", item.Date);
worksheet.Cells["E" + i].Value = item.e;
worksheet.Cells["F" + i].Value = item.f;
worksheet.Cells["G" + i].Value = item.g;
i++;
}
package.SaveAs(ReportFile);
ret = true;
}
}
catch (Exception ex)
{
LibraryLogger.LoggerSoftwareUtility.Error(string.Format("GenerateExcel Exception : {0}", ex));
throw ex;
}
return ret;
}

Retain the source template when saving slides in ppt

I am trying to save selected slide so it doesnt retain my source template. how do i retain the existing template while i save the slides
private void SaveSelectedSlide_Click(object sender, RibbonControlEventArgs e)
{
try
{
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
temporaryPresentation.Slides.Paste();
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
}
catch (COMException Ex)
{
Debug.WriteLine("Some problem" + Ex.Message + Ex.StackTrace);
MessageBox.Show("PLease enter text ");
}
}
I think I got what you want. When pasting the new slide, save the new SlideRange. Afterwards assign the design of the source slide.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
SlideRange sr = temporaryPresentation.Slides.Paste(); // get newly created slideRange
sr.Design = sourceSlide.Design; // manually set design
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
It worked for me. Please let me know if this is the expected behaviour!

Unable to update excel (.xls) file in WCF deployed on Windows server 2008 R2

This issue is specific to a case, when i am trying to update an existing excel file via WCF. Please note that i am able to read excel files and the issue only occurs when i try to update any excel file. Also, this update logic works perfectly fine on my development environment (WinXP where as production environment is Windows server 2008 R2).
I have tried the steps mentioned in Borgon's Blog (http://hopschwiiz.blogspot.com/2011/02/automating-excel-2007-on-windows-server.html) as well but without any luck.
I am using .Net 3.5, SQL Server 2008 & SL 3.0.
As requested have added the codes...
string[] strArray;
string fileName = null;
System.Array myvalues = null;
Microsoft.Office.Interop.Excel.Application ExcelObj = null;
try
{
fileName = System.Configuration.ConfigurationManager.AppSettings["FileLocation"].ToString();
fileName += "JobDetails.xls";
ExcelObj = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook theWorkbook = (Excel.Workbook)ExcelObj.Workbooks.Open(fileName, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "", true, false, 0, false, true, false);
Excel.Sheets sheets = theWorkbook.Worksheets;
for (int sheetNum = 1; sheetNum <= sheets.Count; sheetNum++)
{
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(sheetNum);
for (int i = 8; i <= 50; i++)
{
Excel.Range range = worksheet.get_Range("A" + i.ToString(), "AI" + i.ToString());
myvalues = (System.Array)range.Cells.get_Value(Type.Missing);
strArray = ConvertToStringArray(myvalues);
if (strArray[1].Equals("PSA Id") && strArray[2].Equals("Member Name") && strArray[3].Equals("Project Name"))
{
int j = i;
worksheet.Cells[j, 5] = Month; // Updated Month in the excel file.
foreach (MemberShift item in listOfJobPlan)
{
j++;
worksheet.Cells[j, 2] = item.MemberID.ToString("D" + 6);
worksheet.Cells[j, 3] = item.MemberName;
worksheet.Cells[j, 4] = inGroupName;
}
break;
}
}
}
}
catch (Exception ex)
{
string Log = "DataService";
if ((!(EventLog.SourceExists(Log))))
EventLog.CreateEventSource(Log, Log);
EventLog logEntry = new EventLog();
logEntry.Source = Log;
logEntry.WriteEntry("Message : " + ex.Message + "\n StackTrace : " + ex.StackTrace, EventLogEntryType.Error);
return false;
}
finally
{
ExcelObj.Workbooks.Close();
}
return true;
Check to see what user the Website is running as and then make sure that user has the appropriate permissions to edit the files.

Categories

Resources