I have an excel sheet with 47 columns and about 100 rows. I have a Windows form application with a text field, a button and a label.
Here's what I am trying to do:
When I paste a number into the text box and click the button, it searches the entire excel sheet and fetches the row and column of where that particular string is in the sheet (row, column). This is working fine. I am ok with the performance. Here's what I'd actually like to do -
After I get where the searched string is, I'd like to go to the 45th column, of that same row and get the string from that cell, and display it in the label.
Here's my code (Nothing I did is working!)
string File_name = "C:\\Users\\v-nikken\\Documents\\My Received Files\\Case Wellness.xlsx";
Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook oWB;
Microsoft.Office.Interop.Excel.Worksheet oSheet;
try
{
object missing = System.Reflection.Missing.Value;
oWB = oXL.Workbooks.Open(File_name, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing);
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Worksheets[1];
Microsoft.Office.Interop.Excel.Range oRng = GetSpecifiedRange(textBox_SRNumber.Text, oSheet);
if (oRng != null)
{
//THIS IS THE LOGIC I HAVE TO TAKE VALUE FROM THE CELL TO THE LABEL
//AND OBV IT ISN'T WORKING
int IRPlace = Convert.ToInt32(oRng.Column) + 46; //This is obv wrong
label_IRMet.Text = Convert.ToString(oSheet.Cells[Convert.ToInt32(oRng.Row), IRPlace]); //This also
label_scope_sent.Text = IRPlace.ToString();
}
else
{
MessageBox.Show("Case number not found!", "Please try again");
}
oWB.Close(false, missing, missing);
oSheet = null;
oWB = null;
oXL.Quit();
}
catch (Exception ex)
{
}
Sorry about the formatting. The code section wasn't working for some reason.
Please help!!
Windows 10 - Excel 2016 - VS 2017 - .net 4.6.1
Microsoft.Office.Interop.Excel.Range valueForLabel=(Microsoft.Office.Interop.Excel.Range)yourSheet.Cells[oRng.Row,IRPlace];
string labelText=valueForLabel.Value.ToString();
Related
But it is works fine in English OS.
Also it is returns the correct value for Excel and Power point document in English OS as well as Japanese OS.
Only the problem am facing page count for Word document in Japanese OS
I have tried three type of code but still i'm getting total Page count as 1 only.
References version: Microsoft.Office.Interop.Word Version 15.0.0.0
Visual studio : 2013
Microsoft office : 2016
Method :1:-
Microsoft.Office.Interop.Word.ApplicationClass appWordPageCount = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document DocPageCount = null;
Microsoft.Office.Interop.Word.WdStatistic staticPages = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
object missing = System.Reflection.Missing.Value;
DocPageCount = appWordPageCount.Documents.Open(fileNames);
wordPageCount = DocPageCount.ComputeStatistics(staticPages, ref missing); // fetches page count of word files
Method :2
Microsoft.Office.Interop.Word.Application appWordPageCount = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document DocPageCount = null;
DocPageCount = appWordPageCount.Documents.Open(wordFile);
wordPageCount = DocPageCount.ActiveWindow.ActivePane.Pages.Count;
Method :3
Microsoft.Office.Interop.Word.ApplicationClass appWordPageCount = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document DocPageCount = null;
Microsoft.Office.Interop.Word.WdStatistic staticPages = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
DocPageCount = appWordPageCount.Documents.Open(ref fileNames, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref encoding, ref missing, ref missing, ref missing, ref missing, ref missing);
wordPageCount = DocPageCount.ComputeStatistics(staticPages, ref missing);
Thanks in advance for your guidances.
When Word application view mode is "Web layout" then, it always returning page count as 1.
there are three three view mode in it, Read,Print Layout, Web Layout.
So while getting page count of word document , the mode should be in Print Layout.
I am currently trying to edit cells of an excel spreadsheet object with c# interop. I inserted it in a word document as an object.
Until there i didn't succeed to programm anything that really works. I'm able to select the component but i can't open it to edition and then reach grid's cells.
I use a button control in a custom office ribbon to launch edit. Here is my method:
public void EditTable(Office.IRibbonControl control)
{
Word.Application oWordApp = (Word.Application)Marshal.GetActiveObject("Word.Application");
Word.Document oWordDoc = oWordApp.ActiveDocument;
Word.Bookmark ReqsBookmark = DocumentHelper.GetBookmark("test");
ReqsBookmark.Select();
}
The only way i know to access a specific object with interop is with bookmarks.
Does anybody have an idea of how doing such a thing?
In Word, an Excel worksheet (workbook) is "wrapped" in an OLE control that is a member of the InlineShapes or Shapes collection. So you need the AddOLEObject method of the collection you want to use.
Access to the object model of the OLE server (Excel) is through the OLEFormat property of the InlineShape or Shape. So your code would be something like the sample below.
Note that although you say this is a VSTO project, the code you show us is not VSTO. You're starting up a new instance of the Word.Application, but the VSTO Add-in would be running in-process. My code is VSTO code, but can certainly be adjusted for other situations...
{
Word.Document doc = Globals.ThisAddIn.app.ActiveDocument;
object oRngTarget = Globals.ThisAddIn.app.Selection.Range;
//object oRngTarget = DocumentHelper.GetBookmark("test").Range;
object oOLEClass = "Excel.Sheet.12";
object oFalse = false;
Word.InlineShape ils = doc.InlineShapes.AddOLEObject(ref oOLEClass, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref oRngTarget);
Word.OLEFormat olef = ils.OLEFormat;
System.Globalization.CultureInfo oldCI= System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Excel.Workbook wb = (Excel.Workbook)olef.Object;
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets[1];
try
{
ws.get_Range("A1").Value2 = "New category";
ws.get_Range("B1").Value2 = 6.8;
}
catch (Exception ex)
{
System.Diagnostics.Debug.Print(ex.Message);
}
finally
{
ws = null;
wb = null;
ils = null;
doc = null;
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}
}
To later work with a spreadsheet in the Word document, you basically follow the same principle: declare and instantiate a InlineShape.OLEFormat object, Activate it, then cast olef.Object to an Excel.Workbook:
olef.Activate();
Excel.Workbook wb = (Excel.Workbook)olef.Object;
I finally succeeded thanks to this post about modify an embedded Excel object inside a Word doc
Here's the c# method if anybody need it one day:
{
Word.Document oWordDoc = Globals.ThisAddIn.Application.ActiveDocument;
Excel.Workbook oOLE = null;
Excel.Worksheet oSheet = null;
Word.InlineShapes ils = oWordDoc.InlineShapes;
ils[1].OLEFormat.Activate();
oOLE = ils[1].OLEFormat.Object;
oSheet = oOLE.Worksheets[1];
oSheet.get_Range("A1").Value = "I did it too!";
}
Thank you again #CindyMeister for your answer, it helped me to understand how it really works.
Is there a way to embbed outlook mailitems into word document programatically from a Outlook Mailitem List.??
I am trying to achieve something like this
Word.Application wdApp = new Word.Application();
Word.Document wdDoc = wdApp.Documents.Add(ref missing, ref missing, ref missing,
ref missing);
foreach(Outlook.MailItem olMail in mailAttachments)
{
//Paste/embbed this olMail into the word document
}
Ya Finally i found an effective solution
I used the InlineShapes.AddOLEObject method
My solution:
static void creatDocument(List<Outlook.MailItems> mailAttachments)
{
string userprofile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
object missing = System.Reflection.Missing.Value
object start=0;
object end =0;
object classType ="{00020D0B-0000-0000-C000-000000000046}";
object fileName;
object linkToFile = false;
object displayAsIcon = true;
object iconFileName = Path.Combine(userprofile,"Pictures\MailIcon.ico");
object iconIndex =0;
object iconLabel;
object range;
Word.Application wdApp=new Word.Application();
Word.Document wdDoc = wdApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
Range rng = wdDoc.Range(ref start,ref missing);
foreach(outlook.MailItem olMail in mailAttachments)
{
olMail.SaveAs(Path.Combine(userprofile,"Documents\TemperoraySave") + CleanFileName(olMail.Subject) + ".msg" ,Outlook.OlSaveAsType.olMsg);
fileName = Path.Combine(userprofile,"Documents\TemperoraySave") + CleanFileName(olMail.Subject) + ".msg"
iconLabel = CleanFIleName(olMail.Subject) + ".msg";
rng = wdDoc.Content;
rng.Collapse(WdCollapseDirection.wdCollapseEnd);
range = rng;
wdDoc.InLineShapes.AddOLEObject(ref classType,ref fileName,ref linkToFile,ref displayAsIcon,ref iconFIleName,ref iconIndex,ref iconLabel,ref range);
var mailRanger = wdDoc.Paragraphs.Add();
mailRanger.Format.SpaceAfter =10f;
}
}
private static string CleanFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
Nope. The Word object model doesn't provide anything for that. Instead, you may consider using the CustomDocumentPropertiesenter link description here collection for storing your custom data. For example, you may save the message as an .msg file and save the path to the file or the ID of the record in the database to a custom document property. After, when you need to open a message you can get the ID or path for retrieving the email message.
You can't embed the source text of the emails, but you can copy the MailItem.HTMLBody or MailItem.Body (text) values and insert them into the Word document.
I'm trying to figure out how to programmatically insert mail mergefield into hyperlink in a word document.
In ms word application this is easily accomplished with the following code when in code-view(ALT+F9):
{HYPERLINK "http://example.com?id={MERGEFILED ID}"}
I consulted stackoverflow and google but came up empty-handed.
How could I accomplish something like above snippet via C# word interoperability library?
Right now this is what I have:
using mso = Microsoft.Office.Interop.Word;
public class Test
{
public void GenerateDynamicHyperlinkWithMergeField()
{
mso.Application app = new mso.Application();
object missing = System.Reflection.Missing.Value;
mso.Document doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
mso.Range range = app.Selection.Range;
// this is hyperlinked correctly
mso.Hyperlink hl = document.Hyperlinks.Add(range, "http://example.com?id=", ref missing, ref missing, "textToDisplay", ref missing);
// this mergfield is outside of hyperlink
mso.MailMerge merge = app.ActiveDocument.MailMerge;
mso.MailMergeField mf = merge.Fields.Add(range, "id");
// inserts mergefield code into hyperlink, but not as recognizable code by word application
mso.Hyperlink hl2 = document.Hyperlinks.Add(range, "http://example.com?id=" + mf.Code.Text, ref missing, ref missing, "textToDisplay", ref missing);
}
}
Any help would be much appreciated.
UPDATE:
To clarify what result is expected in word document;
I want this: {HYPERLINK "http://example.com?id={MERGEFILED ID}"}
But I get this with the above function: {HYPERLINK "http://example.com?id="}{MERGEFILED ID}
Try this:
string myLink = "http://example.com?id=" + mf.Code.Text;
mso.Hyperlink hl2 = document.Hyperlinks.Add(range, myString, ref missing, ref missing, "textToDisplay", ref missing);
This might be a red herring, but have you noticed it says MERGEFILED and not MERGEFIELD?
I only bring it up because it's in all instances you mention it.
I have managed to keep Microsoft Word's track revisions property on. It is working fine.
How do I do the same for MS Excel 2007 and above? Follwing is my code for word (which is working fine) and next is for Excel that I am trying to execute.
Word:
Word.Application app = new Word.Application();
Word.Document tempDoc = app.Documents.Open(path);
tempDoc.TrackRevisions = true;
tempDoc.Protect(typ, ref missing, ref password, ref missing, ref missing);
Excel:
Excel.Application ex_APP = new Excel.Application();
Workbook wrk = ex_APP.Workbooks.Open(path);
not able to go past this. When I try doing
wrk.
I don't get property as trackReviosons.
This is the way I am currently doing it it seems to work really well
using Excel = Microsoft.Office.Interop.Excel;
Then you get active workbook
//Gets Excel and gets Activeworkbook and worksheet
Excel.Application oXL;
Excel.Workbook oWB;
Excel.Worksheet oSheet;
oXL = (Excel.Application)Marshal.GetActiveObject("Excel.Application");
oXL.Visible = true;
oWB = (Excel.Workbook)oXL.ActiveWorkbook;
docProps = oWB.CustomDocumentProperties