i'm trying to make a program that inserts data into specific places in existing word document and saves a copy of it.
and i have no clue how to do it , and i cant find any good resource on office 2010 automating.
can anyone point me in the right direction and/or give me some examples.
thanks in advance.
found a solution will add an answer later on
Here is how i did it , it may not be the best way , but its working !
add references to the office interop
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
//defines new excel and workd apps
var ap = new Word.Application();
var excelApp = new Excel.Application();
// defines new excel worksheet & workbooks
Excel.Workbook exBook;
Excel.Worksheet xlWorkSheet;
// should the excell/word apps be visible ?
excelApp.Visible = false;
ap.Visible = false;
//defining the index numbers of our content controls that are in the word template
// index numbers start from 1 and are numbered by order of creation
object Price, Name, address;
Price = 1;
Name = 2;
address = 3;
// here we open the excell file
exBook = excelApp.Workbooks.Open(#"C:\test.xls");
// and we open the first worksheet
xlWorkSheet = exBook.Worksheets.get_Item(1);
Excel.Range range ;
//here we select the first worksheet and make it active
Excel._Worksheet workSheet = (Excel.Worksheet) excelApp.ActiveSheet;
//we open the word document
var doc = ap.Documents.Open(#"C:\test.dotx", ReadOnly: false, Visible: false);
// and we assign the content controls
var dPrice = doc.ContentControls.get_Item(ref Price);
var dName = doc.ContentControls.get_Item(ref Name);
var dAddress = doc.ContentControls.get_Item(ref address);
doc.Activate();
range = xlWorkSheet.UsedRange;
// here we define the columns that we are going to select
object t, P , E , K, N,M,J;
P = "P";
E = "E";
K = "K";
J = "J";
N = "N";
M = "M";
// and here we loop trought the rows of the excell worksheet
// IMPORTANT! excell rows count starts from 1 and not from 0 !
for (int i =1; i< Convert.ToInt16(Settings1.Default.copies) ;i++)
{
t = i;
// here we get the value if cell t(1..2..3..etc), P
var dummy = (range.Cells[t, P] as Excel.Range).Value2;
// here we insert the content of the cell to the content control
dPrice.Range.Text = ": " + Convert.ToString(dummy) + " лв";
dName.Range.Text = ": " + (string)(range.Cells[t, E] as Excel.Range).Value2;
// same thing here
var city = (string) (range.Cells[t, J] as Excel.Range).Value2;
var address1 = (string) (range.Cells[t, K] as Excel.Range).Value2;
var city2 = (string) (range.Cells[t, M] as Excel.Range).Value2;
var address2 = (string) (range.Cells[t,N] as Excel.Range).Value2;
if (!string.IsNullOrEmpty(city2) && city2 != " " && !string.IsNullOrEmpty(address2) && address2 != " ")
{
dAddress.Range.Text = ": " +city.Normalize() + " " + address1.Normalize() + " , " + city2.Normalize() + " " + address2.Normalize() ;
}
else
{
dAddress.Range.Text = ": " + city.Normalize() + " " + address1.Normalize();
}
try
{
//here we try to save the word document as a pdf file
object name = #"C:\t\test"+i+".pdf";
object FileFormat = WdSaveFormat.wdFormatPDF;
doc.SaveAs(ref name, ref FileFormat);
}
catch (Exception ex)
{
MessageBox.Show("Exception Caught: " + ex.Message +" source "+ ex.Source.ToString());
}
}
// here quit word without saving the changes to the template
ap.Quit(SaveChanges: false, OriginalFormat: false, RouteDocument: false);
excelApp.Quit();
// and we release the objects
System.Runtime.InteropServices.Marshal.ReleaseComObject(ap);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
i hope this was helpful to someone :)
Related
I have this code:
function _1() {
var aa = SpreadsheetApp.getActiveSpreadsheet();
var sheet = aa.getSheets()[0];
var cell = sheet.getRange("k1");
var cell = sheet.getvalue("a" + cell + ")");
};
In cell k1 there is a number (variable). I want to use this cell in my function, but its not work for me.
You entire code is correct, except last line:
var cell = sheet.getvalue("a" + cell + ")")
You don't need to import range value again in your getValue and it will cause error, and below is the correct execution by convert value to string (*remove ; after } ):
function test_1() {
var aa = SpreadsheetApp.getActiveSpreadsheet();
var sheet = aa.getSheets()[0];
var cell = sheet.getRange("B2").getValue();
cell = cell.toString() + "a"
Logger.log(cell);
}
Answer
getValue() does not take any input parameter. Join the strings later
Solution
I attach you a function that reads the number in B2 (X) and writes a string in AX.
function test_1() {
var aa = SpreadsheetApp.getActiveSpreadsheet();
var sheet = aa.getSheets()[0];
var B2 = sheet.getRange("B2").getValue();
var cell = "A" + B2.toString()
sheet.getRange(cell).setValue('test')
}
References
Range.getValue()
Range.setValue(value)
I am pretty new to Selenium and learning through self study. Any help will be appreciable.
Currently I am using
String data = wb.getSheetAt(sheetnum).getRow(row).getCell(col).getStringCellValue();
It is working fine for String but not for numeric. I have a cell value of '500' and I want to fetch it. Please help.
Try out following code :
public void readfile(String filepath, String filename, String sheetname) throws IOException {
File file = new File(filepath+"\\"+filename);
FileInputStream fis = new FileInputStream(file);
// for creating .xlsx workbook
Workbook wb = new XSSFWorkbook(fis);
// for reading the sheet by its name
Sheet sh = wb.getSheet(sheetname);
// find the total rows in sheet
int rowcount = sh.getLastRowNum() - sh.getFirstRowNum();
// create a loop to create
for (int i = 0; i < rowcount + 1; i++) {
Row row = sh.getRow(i);
// create a loop to print cell values
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(row.getCell(j).getStringCellValue() + " ");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int)row.getCell(j).getNumericCellValue() + " ");
break;
}
}
System.out.println();
}
}
Hope it will help you.
Double data = wb.getSheetAt(sheetnum).getRow(row).getCell(col).getNumericCellValue();
I have one table and i want to retrieve all the value from one column(mailid) .In the table two column are available that is id and mailid.
I want to send mail to all the persons whose mail id is available in this column.
mstEmpAdmin m = new mstEmpAdmin();
var m2=(from e in db.mstEmpAdmins
select new
{
txtEmpAdminEmailId = e.txtEmpAdminEmailId,
});
CustomMailService mail = new CustomMailService();
string Subject = "Domestic Travel Request";
string Body = "Hi Sir/Madam,My ";
mail.Mail(m2,Subject, Body);
Form the above code it is showing error in last line ,what i am thinking is i will store al the mail id in one object then i will pass that object while sending mail.
Can I do like that ? Any solution for this ?
I got the output .
List<mstEmpAdmin> adminlist = (from st in db.mstEmpAdmins
select st).ToList();
foreach (var item in adminlist)
{
string Subject = "Request for Business Card";
string Body = "Hello Sir/Madam ," + "\n" + " " + bc.txtFirstName + " " + "You have requested for Business Card" + " " + "Total no of Quantity :" + bc.intQuantity + " ";
CustomMailService mail = new CustomMailService();
mail.Mail(item.txtEmpAdminEmailId, Subject, Body);
}
Please see below code its working fine and searching for all excel files in given directory. But I am not able to understand this code
Doubt : NoOfFolders(Iterator1) is a dynamic array and when again function is called fnFolderStructure , NoOfFolders array is again created. But even values NoOfFolders(0) and NoOfFolders(1) changed but still when again its is called with previous values.
How it is able to retain values even after writing of NoOfFolders(Iterator1).
fnCheckFiles("C:\Temp\Sahil")
Function fnFolderStructure(sAddress)
i=0
Dim NoOfFolders()
Set objFSO1 = CreateObject("Scripting.FileSystemObject")
Set objFolder2 = objFSO1.GetFolder(sAddress)
Set FolderIn=objFolder2.SubFolders
Set FileIn=objFolder2.Files
' If FileIn.Count>0 Then
' fnCheckFiles(sAddress)
' End If
If FolderIn.Count>0 Then
y=FolderIn.Count
ReDim NoOfFolders(y-1)
For Each objSubfolder in FolderIn
NoOfFolders(i)= objSubfolder.Name
i=i+1
Next
For Iterator1 = 0 To y-1
sPath1=sAddress&"\"&NoOfFolders(Iterator1)
fnCheckFiles(sPath1)
Next
' Set colSubfolders = FolderIn.Subfolders
' Call fnFolderStructure(sPath1)
End If
End Function
Function fnCheckFiles(sAddress)
Set objFSO1 = CreateObject("Scripting.FileSystemObject")
Set objFolder4 = objFSO1.GetFolder(sAddress)
''sFileName=objFolder4.Name
For Each objFile In objFolder4.Files
sFileName=objFile.Name
if (InStr(1,sFileName,"xlsx",1)) then
msgbox objFile.Name
End IF
Next
if objFolder4.SubFolders.Count>0 then
fnFolderStructure(sAddress)
End if
End Function
How it is able to retain values even after writing of
NoOfFolders(Iterator1)
The array is not being written to by that statement. The array NoOfFolders is used in four places...
1) Declares the value as a dynamic array
Dim NoOfFolders()
2) Redimensions the variable to match the size of the number of folder names it will hold
ReDim NoOfFolders(y - 1)
3) Assigns the name of a folders to the corresponding position in the array. This is the only place where values are written to the array.
NoOfFolders(i) = objSubFolder.Name
4) Reads the name of a folder from the array to build a path of a sub-folder
sPath1 = sAddress & "\" & NoOfFolders(Iterator1)
====================================================================================================================*/
def getTagValue(def filepath, def tagName,log)
{
def tagValue = ""
try
{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance()
DocumentBuilder docBuilder = docFactory.newDocumentBuilder()
Document doc = docBuilder.parse(filepath)
// Get the root element
Node company = doc.getFirstChild()
NodeList nodes = doc.getElementsByTagName(tagName)
//log.info "Nodes length :" +nodes.getLength()
Node node = nodes.item(0)
//log.info node.getTextContent()
tagValue = node.getTextContent()
if(tagValue == "")
{
tagValue = "tag not found"
}
}
catch(Exception e)
{
log.error e.message
tagValue = "tag not found"
}
return tagValue
}
==============================
def List readXpaths(def expectedExcelPath, def expectedExcelSheet, log, context)
{
Fillo.Connection con=getFilloConnection(expectedExcelPath,log)
String sQuery="Select * from "+expectedExcelSheet+" where TestCaseName='"+context.testCase.name+"'"
//log.info sQuery
Recordset rs=getRecordSet(con,sQuery,log)
List<String> colList=rs.getFieldNames()
colList.remove("TestCaseName")
colList.remove("DATA_SET")
colList.remove("RUN")
List<String> xpaths=new ArrayList<String>()
while(rs.next())
{
for(String str:colList)
{
if(rs.getField(str)!="")
{
xpaths.add(rs.getField(str))
}
}
}
return xpaths;
}
I am learning visual basic .net and I am attempting to translate some java source code to a vb.net project. The project reads mp3 details and then splits the file accurately according to the frameheader details etc.
My question relates to reading the frame header of mp3 files. I understand that the frame details are contained in the first 4 (32-bits) bytes of a frame and certain bits represent certain values as detailed here: http://www.mp3-tech.org/programmer/frame_header.html
Using FileStream I have been able to read this data and display it in binary within a text box.
I am looking for help on reading the bits and assigning them to variables within my class. I am not sure what would be the correct procedure to do this as some values as 1, 2 or 4 bits in length e.g. bits 19-20 = MpegType, bits 12-15 = BitrateIndex, bit 9 = Padding etc.
I have looked at similar projects available on codeproject.com but I do not understand how they have achieved the above.
Any help is much appreciated.
EDIT:
Here is the main sub so far, I have not included the code declaring variables and properties etc.
Public Sub decode()
Dim fs As FileStream
Dim bytes(3) As Byte
fs = New FileStream(mFilename, FileMode.Open, FileAccess.Read)
If fs.CanRead Then
fs.Read(bytes, 0, bytes.Length)
For i As Integer = 0 To bytes.Length - 1
Form1.RichTextBox.Text += Convert.ToString(bytes(i), 2).PadLeft(8, "0"c) & vbCrLf
Next
fs.Close()
fs.Dispose()
Else
MsgBox("File CANNOT be read!!!")
End If
End Sub
When this is run the output in the rich text box is as follows:
11111111
11111010
10110011
01001100
I want to read through these bits and assign the appropriate values to the variables e.g.
Read the first 12 bits for sync value.
Read bit 13 for mpegID value.
Read bit 14 and 15 for layerID value etc.
Hope that is clearer.
The java code is as follows:
public FrameHeader() {
this.header32 = 0;
valid = false;
}
public FrameHeader(int header32) {
this.header32 = header32;
decode();
}
public void setHeader32(int header32) {
this.header32 = header32;
decode();
}
private void decode() {
mpegID = (header32 >> 19) & 3;
layerID = (header32 >> 17) & 3;
crc16used = (header32 & 0x00010000) == 0;
bitrateIndex = (header32 >> 12) & 0xF;
samplingrateIndex = (header32 >> 10) & 3;
padding = (header32 & 0x00000200) != 0;
privateBitSet = (header32 & 0x00000100) != 0;
mode = (header32 >> 6) & 3;
modeExtension = (header32 >> 4) & 3;
copyrighted = (header32 & 0x00000008) != 0;
original = (header32 & 0x00000004) == 0; // bit set -> copy
emphasis = header32 & 3;
valid = (mpegID != ILLEGAL_MPEG_ID) && (layerID != ILLEGAL_LAYER_ID) && (bitrateIndex != 0)
&& (bitrateIndex != 15) && (samplingrateIndex != ILLEGAL_SR);
if (valid) {
samplingrateHz = SAMPLING_RATES[samplingrateIndex];
if (mpegID == MPEG2_ID)
samplingrateHz >>= 1; // 16,22,48 kHz
if (mpegID == MPEG25_ID)
samplingrateHz >>= 2; // 8,11,24 kHz
channels = (mode == MODE_MONO) ? 1 : 2;
bitrateKBPS = BITRATE_MAP[mpegID][layerID][bitrateIndex];
if (layerID == LAYER1_ID) {
// layer 1: always 384 samples/frame and 4byte-slots
samplesPerFrame = 384;
bytesPerSlot = 4;
}
else {
// layer 2: always 1152 samples/frame
// layer 3: MPEG1: 1152 samples/frame, MPEG2/2.5: 576
// samples/frame
samplesPerFrame = ((mpegID == MPEG1_ID) || (layerID == LAYER2_ID)) ? 1152 : 576;
bytesPerSlot = 1;
}
frameSize = ((bitrateKBPS * 125) * samplesPerFrame) / samplingrateHz;
if (bytesPerSlot > 1)
frameSize -= frameSize % bytesPerSlot;
if (padding)
frameSize += bytesPerSlot;
}
}
Here is a detailed explanation of frames and a formula on how data is held in the header, the first 4 bytes of a frame.
I am not sure what you are trying to accomplish but, just in case, here you go. There is no point in reinventing the wheel.
.Net has class called BitArray that you would use to store your bits.
I have come across a similar project that uses a function to converts bits to string. I've combined this code with another example I found that changed a binary string to integer. Interested to hear of alternative methods?
Public Function BinaryToInteger(ByVal objBitArray As BitArray, ByVal intStart As Integer, ByVal intEnd As Integer) As Integer
Dim BinaryString As String
Dim BinaryNum As Integer
Dim BitCount As Short
BinaryString = ""
For i As Integer = intStart To intEnd
BinaryString &= IIf(objBitArray.Item(i), "1", "0")
Next
For BitCount = 1 To Len(BinaryString)
BinaryNum = BinaryNum + (CDbl(Mid(BinaryString, Len(BinaryString) - BitCount + 1, 1)) * (2 ^ (BitCount - 1)))
Next BitCount
BinaryToInteger = BinaryNum
End Function