how to split into lines c# word document
Help me to solve this problem - how to insert text into a Word document so that the first line of each sheet has an inscription, for example "continuation of the table". I suppose to do it like this...Find the lines of each of the pages and on each page find the first line and insert. Maybe it can be done differently ... more gracefully) But even with my approach, not all lines are displayed.
try
{
for (int ii = 1; ii < LineCount; ii++)
{
CurrentPageNumber = (Convert.ToInt32(ii.ToString()));
NextPageNumber = (Convert.ToInt32((ii + 1).ToString()));
// Get start position of current page
Start = oWord.Selection.GoTo(ref What, ref Which, ref CurrentPageNumber, ref Miss).Start;
// Get end position of current page
End = oWord.Selection.GoTo(ref What, ref Which, ref NextPageNumber, ref Miss).End;
var rng_page = docDocument.Range(Start, End);
string textLine = rng_page.Text;
Console.WriteLine(textLine);
var line_rng= docDocument.Range(unit);
string textline_line = line_rng.Text;
//Console.WriteLine(textline_line);
}
}
catch (Exception ex)
{
_ = ex.Message;
}
Thank you.
do you know?
how many words do you know
See also questions close to this topic
-
C# - Adding condition to func results in stack overflow exception
I have a func as part of specification class which sorts the given iqueryable
Func<IQueryable<T>, IOrderedQueryable<T>>? Sort { get; set; }
When i add more than one condition to the func like below , it results in stack overflow exception.
spec.OrderBy(sc => sc.Case.EndTime).OrderBy(sc => sc.Case.StartTime);
The OrderBy method is implemented like this
public ISpecification<T> OrderBy<TProperty>(Expression<Func<T, TProperty>> property) { _ = Sort == null ? Sort = items => items.OrderBy(property) : Sort = items => Sort(items).ThenBy(property); return this; }
Chaining or using separate lines doesn't make a difference.
This problem gets resolved if I assign a new instance of the specification and set it's func, but i don't want to be assigning to a new instance everytime. Please suggest what am i missing here and how to reuse the same instance (if possible).
-
How to projection fields for a dictionary (C#, MongdoDB)
I am trying my luck here, I have a model which is like the following
public class RowData : BaseBsonDefinition { . [BsonExtraElements] [BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)] public Dictionary<string, object> Rows { get; set; } = new(StringComparer.OrdinalIgnoreCase); . }
In result, the schema in the MongoDB looks like
{ "_id": { "$binary": { "base64": "HiuI1sgyT0OZmcgGUit2dw==", "subType": "03" } }, "c1": "AAA", "c8": "Fully Vac", "c10": "", }
Those c1, c8 and c10 fields are keys from the dictionary, my question is how to dynamic project those fields?
I tried
Builders<RowData>.Projection.Exclude(p => "c1")
It seems the MongoDB driver can not handle a value directly.
Anyone could point me in the correct direction?
Thanks,
-
How do I add new DataSource to an already Databinded CheckBoxList
i'm building a web form that show Database's item(Tables, Rows, FK,...)
I have a CheckBoxList of Tables (
chkListTable
) which will show a new CheckBoxList of Rows (chkListRow
) everytime I SelectedIndexChanged fromchkListTable
. The problem is i can show the items fromchkListTable
with 1 selected item. But i don't know how to showchkListRow
if multiple item fromchkListTable
are selected.Here are my codes:
aspx
:<div> <asp:Label ID="Label2" runat="server" Text="Table: "></asp:Label> <asp:CheckBoxList ID="chkListTable" runat="server" DataTextField="name" DataValueFeild="name" AutoPostBack="true" OnSelectedIndexChanged="chkListTable_SelectedIndexChanged"> </asp:CheckBoxList> </div> <div> <asp:CheckBoxList ID="chkListRow" runat="server" DataTextField="COLUMN_NAME" DataValueField="COLUMN_NAME" RepeatDirection="Horizontal"> </asp:CheckBoxList> </div>
aspx.cs
:protected void chkListTable_SelectedIndexChanged(object sender, EventArgs e) { tableName.Clear(); foreach (ListItem item in chkListTable.Items) { if(item.Selected) { tableName.Add(item.Text.Trim()); } } for(int i = 0; i < tableName.Count; i++) { String query = "USE " + dbname + " SELECT * FROM information_schema.columns" + " WHERE table_name = '" + tableName[i] + "'" + " AND COLUMN_NAME != 'rowguid'"; chkListRow.DataSource = Program.ExecSqlDataReader(query); chkListRow.DataBind(); Program.conn.Close(); } }
Program.cs
:public static bool Connect() { if (Program.conn != null && Program.conn.State == ConnectionState.Open) Program.conn.Close(); try { Program.conn.ConnectionString = Program.constr; Program.conn.Open(); return true; } catch (Exception e) { return false; } } public static SqlDataReader ExecSqlDataReader(String query) { SqlDataReader myreader; SqlCommand sqlcmd = new SqlCommand(query, Program.conn); sqlcmd.CommandType = CommandType.Text; if (Program.conn.State == ConnectionState.Closed) Program.conn.Open(); try { myreader = sqlcmd.ExecuteReader(); return myreader; myreader.Close(); } catch (SqlException ex) { Program.conn.Close(); return null; } }
I want my display to be like this:
[x]Table1 [x]Table2 [ ]Table3 [ ]Row1(Table1) [ ]Row2(Table1) [ ]Row3(Table1) [ ]Row1(Table2) [ ]Row2(Table2)
-
How to name sheets in loop based on FilePath variable using VBA to process tables from Word doc(s)?
The context is that I have a boatload of data dictionaries for various data bases strewn across multiple Word document files. Those files have (among other extraneous information) tables that contain the actual code book parts that I need. I want to be able to open a Word doc containing these data dictionaries (one Word doc might have 4-5 tables corresponding to separate data sets), extract the tables to Excel workbook format, depositing the separate tables to sheets. Ultimately, I will do this for 100+ separate Word documents.
The code below is a good start. It gets tables in separate sheets in an Excel workbook file. From there I will be generating a sheet that will act as an index. That index page will contain a list of variable names that link to the appropriate sheet containing said variable for a specific data set. The index sheet will have a lay out that makes for easy sorting (so columns for original data set name, variable name, maybe others).
I have tried, and failed, to get the code below to name each sheet in a way that will facilitate my end goal without manual editing. Right now it spits them out as "Sheet1,,,,SheetN." I need them to be something like "DictionaryName1,,,DictionaryNameN" where "DictionaryName" is based on the Word file from which they originate. That will make automating the eventual creation of the index page much easier.
Right now, this is set up to have a dialog that asks to select the originating file. Since this needs to be done with so many files, the eventual goal is to instead select a directory and have this all happen for each Word doc in that directory (or select a set of Word docs via giving a path, whatever). Ideally, everything will end up in a single Excel workbook (rather than having separate workbooks per each originating Word doc, which is how this is currently geared). Also, I want to leave the separate sheets as close to unformatted as possible so that I would have the option to chop them back out as plain text .csv files that could be easily ingested by R, SAS, or other stats packages (for automating generation of custom data sets composed of variables from multiple source data sets).
There are other details, such as figuring out an intelligent way to discard tables in the Word docs that are not the data dictionaries (e.g. some of the Word docs contain what is intended to be a table of contents that is formatted as a table), but I'm setting that aside until I get at least this much worked out.
Sub CopyTables() Dim oWord As Word.Application Dim WordNotOpen As Boolean Dim oDoc As Word.Document Dim oTbl As Word.Table Dim fd As Office.FileDialog Dim FilePath As String Dim wbk As Workbook Dim wsh As Worksheet ' make a prompt to select dictionary file... could automate this to do over all files in a directory instead Set fd = Application.FileDialog(msoFileDialogOpen) With fd .Filters.Clear .Filters.Add "Word Documents (*.docx)", "*.docx", 1 .Title = "Choose a Word File" If .Show = True Then FilePath = .SelectedItems(1) Else Beep Exit Sub End If End With On Error Resume Next Application.ScreenUpdating = False ' make new workbook Set wbk = Workbooks.Add(Template:=xlWBATWorksheet) ' start up Word or get it if open Set oWord = GetObject(Class:="Word.Application") If Err Then Set oWord = New Word.Application WordNotOpen = True End If On Error GoTo Err_Handler ' open document up Set oDoc = oWord.Documents.Open(Filename:=FilePath) ' loop over tables from document For Each oTbl In oDoc.Tables ' make a sheet Set wsh = wbk.Worksheets.Add(After:=wbk.Worksheets(wbk.Worksheets.Count)) ' copy/paste table into sheet oTbl.Range.Copy wsh.Paste 'tried using e.g. oTbl.Title, FilePath, etc. here to name the sheets, but no luck... Next oTbl ' gets rid of first sheet Application.DisplayAlerts = False wbk.Worksheets(1).Delete Application.DisplayAlerts = True Exit_Handler: On Error Resume Next oDoc.Close SaveChanges:=False If WordNotOpen Then oWord.Quit End If ' clean up object references Set oTbl = Nothing Set oDoc = Nothing Set oWord = Nothing Application.ScreenUpdating = True Exit Sub Err_Handler: MsgBox "something went wrong... " & Err.Description, vbCritical, "Error: " & Err.Number Resume Exit_Handler End Sub
I am a novice with VBA. Barely ever touch it, but was asked to use it for this. Like mentioned above, there are further steps to complete the overall task. Other than what was previously mentioned, another thing that jumps to mind is that some of the tables that are the data code book parts have headers (as in a first row with the name of the specific data set) while others do not (e.g. the row 1 reads like column names, with varname, var_description, type, format, comments). So that will need to be sorted eventually in order for this task to be reproducible in the future from the source Word docs. Changing the workflow is not an option at this point, unfortunately. I have also considered having the end result simply be a single, large table. That could be accomplished by adding a column(s) to denote source data set and combining all of the separate data code books together. Either way, being able to intelligently name the sheets is my current sticking point.
-
Python: Converting .html file to .docx while keeping text formatting (e.g. bold, italic, etc.)
I want to convert a normal .html file (with some formating such as lists, headings, bold text, etc.) into a .docx file (Word) while actually retaining the formatting as good as possible using this code:
# convert html file into word import pypandoc output = pypandoc.convert(source = "input.html", format='html', to='docx', outputfile="results.docx")
I also tried many other approaches (e.g. the library html2text or win32com.client) but no solution is keeping text formatting (e.g. bold or italic). The only package that managed to keep this formatting was https://blog.aspose.com/2021/11/26/convert-html-to-word-in-python/, but this is not for free.
Is there any solution about how I can keep the formatting (especially bold text) of an .html file when converting it to a .docx (Word) file?
-
max number of vba bookmarks
I am currently working on a Word-document I want to use as a template. This template provides a "structure" including many bookmakrs. The template is filled using these bookmarks, e.g. pictures and texts are inserted at places specified by these bookmarks. It works quite well so far, but when I access my worddocument via excel vba, like:
Set appWD = CreateObject("Word.Application") appWD.Visible = True appWD.documents.Open ThisWorkbook.path & "\" & targetName appWD.documents(targetName).Activate Set mydoc = appWD.ActiveDocument
only 256 bookmarks are displayed in mydoc.bookmarks despite the count of 391.
snipplets of start and end of bookmark list displayed in excel vba
In Word I can access all 391 bookmarks without any problems. In Excel VBA all bookmarks listed in places higher than those 256 are declared unknown. If I try something like the following I get an error stating myBookMark is unknown.
mydoc.Goto(what:=-1, which:=1, name:=myBookMark).Select
Did anybody experience a similiar problem so far or knows a workaround of how to access bookmarks no. 257 - 391?
thanks a lot
-
division of text in lines
hello and thank you for any help I need help
I have this code he reads the 5-10 lines but I need to remake it
f=open("input.txt", encoding='utf-8') lines=f.readlines() for x in range(5,10): print(lines[x])
I am looking for this output
first input second is output image
input
1-100 lines
im search this number search in list
xx = lambda n:n and list(range(n,100,9)) print(xx(num))
output lines is text
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91] [2, 12, 22, 32, 42, 52, 62, 72, 82, 92] [3, 13, 23, 33, 43, 53, 63, 73, 83, 93] [4, 14, 24, 34, 44, 54, 64, 74, 84, 94] [5, 15, 25, 35, 45, 55, 65, 75, 85, 95] [6, 16, 26, 36, 46, 56, 66, 76, 86, 96] [7, 17, 27, 37, 47, 57, 67, 77, 87, 97] [8, 18, 28, 38, 48, 58, 68, 78, 88, 98] [8, 18, 28, 38, 48, 58, 68, 78, 88, 98] [9, 19, 29, 39, 49, 59, 69, 79, 89, 99] [10, 20, 30, 40, 50, 60, 70, 80, 90,100]
just make a square
from 1 to 10 down from 11 to 20 down etc ...
there is text on the lines so that, for example, all 10 texts are combined into one
[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
this is just an example I have a long text of 33 thousand lines
-
Making a block connector in JavaFX
I want to create a blocks that will be connected with a line. It have to be look like in this image.
Or also if this will be hard to do it also can be like that (With straight lines).
I tried to do it but I had some problems. I think I need to do it using onDragDetected and onMouseDragEntered inside FXML for controller check and do some code but I don't know how exactly to do. Also my other problem is that I want to do this blocks movable with mouse drag but if my circle will be inside the block (how I do it) that will make this circle movable with the block but I have to move only line from this circle.
-
C# Open file with default program without stealing focus?
I'd like to open files programmatically with their default program. My problem is I'd like to open lots of files, and don't want to bombard the user with all these pop-ups, so I'd like to open each file minimized while not stealing focus.
The options I've tried with no success are:
ProcessStartInfo.ProcessWindowStyle.Minimized;
which just opens the file normally,- P/Invoke's
CreateProcess
, which opens the process just fine, but can't be used to open files - P/Invoke's
SetWindowPos
, which I've tinkered with but can't seem to crack - Embedding each above idea's
MainWindowHandle
into an already hidden WinForm by callingSetParent(Process.MainWindowHandle, WinForm.Handle);
which works, but each opened file steals focus, opens normally, then gets pulled into the WinForm. I know it's possible to return that focus to what the user was doing, but I intend to open a lot of files so it would be best to run them as in the background as possible.
Is there an easier way to do this? Like potentially open the file within an already hidden service as a child? Or writing/opening a .bat file with any explicit "open minimized no focus" command? Obviously I'm unfamiliar with P/Invoke but I'm willing to learn if it's what's needed! I just don't have enough experience yet to approach this issue from any different angle.
This is also being written in WPF if that helps.
Thank you in advance!
-
Why do Office updates break the Excel interop?
I'm writing Selenium automation in C# in Visual Studio 2019, and have a Microsoft Office 16.0 Object Library COM reference so that I can open Excel sheets and read in data. The version of Excel I'm using is "Microsoft Excel for Microsoft 365 MSO (16.0.13801.21198) 32-bit".
The Excel code works fine until certain Office updates are rolled out to my machine, at which point I start getting this error when trying to open a worksheet:
Unable to cast COM object of type "Microsoft.Office.Interop.Excel.ApplicationClass" to interface type "Microsoft.Office.Interop.Excel._Application". This operation failed because the QueryInterface call on the COM component for the interface with IID "{000208D5-0000-0000-C000-000000000046}" failed due to the following error: Element not found.
I've seen various recommendations to try deleting a registry entry in order to fix this, which have not worked. The only way I can get it working again is to run a Quick Repair on Office 365.
This is happening every week or two, and I have a number of automation developers on my team who have the same issue and need to run a Quick Repair in order to fix it.
Does anyone know exactly what causes this problem? I'd really prefer to develop a solution or workaround for it that doesn't require manually firing off a repair to Office all the time.
Note: I have tried switching to the Excel.Interop nuget package and using that dll instead but I still have the same issue after an Office update.
-
C# Word Interop adding bottom border to paragraph creates a newline I want to get rid of
I'm trying to add a bottom border to my text in order to create an horizontal line just under it. Inserting the line is no problem, but I get a newline just before and don't know how to get rid of it. I would like to insert the line right under my text and to find the cursor located in a new line right after it.
Does someone know how to do it?
Here's the code I'm working with at the moment:
object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\\endofdoc"; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = false; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); oDoc.PageSetup.TopMargin = 36; oDoc.PageSetup.RightMargin = 36; oDoc.PageSetup.BottomMargin = 36; oDoc.PageSetup.LeftMargin = 36; Word.Paragraph titolo; object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; titolo = oDoc.Content.Paragraphs.Add(ref oRng); titolo.Range.Text = "My text"; titolo.Range.Font.Name = "Open Sans"; titolo.Range.Font.Size = 16; titolo.Range.Font.Italic = 0; titolo.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; titolo.Format.SpaceAfter = 24; titolo.Range.InsertParagraphAfter(); Word.Paragraph section1_title; oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range; section1_title = oDoc.Content.Paragraphs.Add(ref oRng); section1_title.Range.Text = "Text I want a line under"; section1_title.Range.Borders[Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleSingle; section1_title.Range.Font.Name = "Open Sans"; section1_title.Range.Font.Size = 12; section1_title.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; section1_title.Range.InsertParagraphAfter(); oWord.Visible = true;
To make stuff clearer, here is what I get and here is what I want. Notice that in the first picture I have a writable line between the text and the line (like I got a \n at the end of "My text").
I also tried to trim the text.
Thanks to anyone answering.
EDIT: Here's the file produced (GoogleDrive link)
EDIT2: Posted complete code. Needs Microsoft.Office.Interop.Word assembly reference to work and using Word = Microsoft.Office.Interop.Word;