I want to have mutple format types in one cell in my workbook. For example I want my A1 cell to display " Name: Aaron Kruger ". When I programmatically add the name "Aaron Kruger" to the template, it automatically makes it bold. So instead it looks like this " Name:Aaron Kruger ". So I want Bold and non-bold both in the same cell. And maybe in the future I will want two different text sizes in the same cell.
Thanks,
Aaron Kruger
Here is the function I created:
public void inputData(int row, int column, string cellName, System.Windows.Forms.TextBox textBox, Excel.Worksheet sheet)
{
sheet.Cells[row, column] = sheet.get_Range(cellName, Type.Missing).Text + " " + textBox.Text; // adds value to sheet
}
Here are the arguments I pass in:
inputData(5, 1, "A5", tbTagNumber, xlSheet);
inputData(6, 1, "A6", tbCustomer, xlSheet);
inputData(7, 1, "A5", tbDataFile, xlSheet);
inputData(3, 6, "F3", tbJobNumber, xlSheet);
inputData(4, 6, "F4", tbMeterSN, xlSheet);
inputData(6, 6, "F6", tbPO, xlSheet);
inputData(7, 6, "F7", tbFlowplate, xlSheet);
inputData(4, 9, "I4", tbElectronicSN, xlSheet);
Range rng1 = ws.getRange("A1","E10");
for(int i=0;i<10;i++)
{
Range rngTst=rng.cells[i,i];
for(int j=0;j<rngTst.get_characters().count;j++)
{
rngTst.application.activecell.get_characters(j,j).font.color
}
}
or
int sFirstFoundAddress = currentFind.FormulaR1C1Local.ToString().IndexOf("NOT FOR CIRCULATION ");
get_Range(excel.Cells[1, 1],
excel.Cells[1, dtData.Columns.Count])
.get_Characters(sFirstFoundAddress, 20).Font.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
Use Microsoft.Office.Interop.Excel.Range which gives you each character as Characters type. Now use its Font and other properties to style them.
Refer an example here: http://www.bloodforge.com/post/Extract-Formatted-Text-From-Excel-Cell-With-C.aspx
Microsoft.Office.Interop.Excel.Range Range = (Microsoft.Office.Interop.Excel.Range)Cell;
int TextLength = Range.Text.ToString().Length;
for (int CharCount = 1; CharCount <= TextLength; CharCount++)
{
Microsoft.Office.Interop.Excel.Characters charToTest = Range.get_Characters(CharCount, 1);
bool IsBold = (bool)charToTest.Font.Bold;
bool IsItalic = (bool)charToTest.Font.Italic;
// other formatting tests here
}
I recorded a macro, it shouldn't be hard to translate it to C#:
ActiveCell.FormulaR1C1 = "Test test"
Range("A1").Select
ActiveCell.FormulaR1C1 = "Test test"
With ActiveCell.Characters(Start:=1, Length:=5).Font
.Name = "Calibri"
.FontStyle = "Regular"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
With ActiveCell.Characters(Start:=6, Length:=4).Font
.Name = "Calibri"
.FontStyle = "Bold"
.Size = 11
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
Related
First. I create a group of 5 labels using a for
for (byte fila = 0; fila < 5; fila++)
{
Label letras = new Label();
letras.Height = alto;
letras.Width = ancho;
letras.BackColor = Color.Blue;
letras.ForeColor = Color.AntiqueWhite;
letras.Font = new Font("Arial", 60);
letras.TextAlign = ContentAlignment.MiddleCenter;
letras.BorderStyle = BorderStyle.FixedSingle;
letras.Left = 200 + (ancho + 20) * fila;
letras.Top = 60;
letras.Text = null;
letras.Visible = false;
letras.MouseMove += new
System.Windows.Forms.MouseEventHandler(this.letras_MouseMove);
this.Controls.Add(letras)
Second. I have a list of words declared as list of strings of 5 characters.
List <string> palabras = new List <string> { "limón", "bufón", "leche", "video",
"guiso",
"dulce", "gusto", "audaz", "vacío", "huevo", "avena", "guapo", "ozono",
"audio",
"zanja", "pausa", "freno", "débil", "hurto", "otoño", "libro", "pluma",
"disco",
"fruta", "melón", "papel", "mapeo", "nuevo", "banco", "tigre", "mundo",
"hueco",
"cable", "funda", "lápiz", "botón", "tonto", "regla", "tipas", "canal" };
I need to call one of them (words) and put each of the characters in a label of the group of labels I created first, in an altered order (5, 3, 1, 2, 4). I ´ve tried with substrings function but I always have errors. ¿Any suggestions?
string is basically an array of char, so you can access specific chars by their index, e.g.
string text = "Hello world!";
// this will write 'H'
Console.WriteLine(text[0]);
I would like to prevent the looping and when i display the card. It should only display my name once and my friends name one. It is constant looping now.
This is what i have declared
int row = 2;
int count = 0;
int num = 0;
int name = 0;
bool=false;
if (CardReader.CANSnr.Equals("8009140003484246"))
{
scan = true;
textBox1.Text = "Welcome Back";
textBox2.Text = "Jonathan";
DateTime theDate = DateTime.Now;
string todaysDate = theDate.ToString("d");
string todaysTime = theDate.ToString("T");
//add Data to to cells
excell_app.addData(row, 1, "Jonathan", "A1", "A1", "#,##0");
excell_app.addData(row, 2, "1", "B1", "B1", "");
excell_app.addData(row, 3, todaysDate, "C1", "C1", "#,##0");
excell_app.addData(row, 4, todaysTime, "D1", "D1", "#,##0");
row++;
}
I don't think there's enough information here to answer your question. You don't have a loop in the provided code, so any perceived looping must be happening at a higher level.
Otherwise, it looks like you have a var (scan) that you could use to prevent multiple scans from happening, if that's what you're after.
...
bool scan = false;
if (!scan && CardReader.CANSnr.Equals("8009140003484246"))
{
scan = true;
...
}
I have an application written in C# that needs to be converted to Python, since I have recently switched to Linux. It's a simple GUI application to manage unknown words while learning a new language. Nevertheless, I need remove_item() function for which I also need find_word() function.
In C#, I would create two following methods:
void Remove()
{
Word word = new Word();
try { word = FindWord(listView1.SelectedItems[0].Text); }
catch { return; }
if (listView1.SelectedItems.Count > 0)
{
try
{
foreach (ListViewItem eachItem in listView1.SelectedItems)
{
words.RemoveAll(x => x.WordOrPhrase == eachItem.Text);
listView1.Items[listView1.Items.Count - 1].Selected = true;
listView1.Items.Remove(eachItem);
}
}
catch { }
ClearAll();
ReadOnlyON();
}
else
{
MessageBox.Show("You have not selected any words!", "Notification", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
ReadOnlyOFF();
WordCount();
Sync();
}
private Word FindWord(string word)
{
return words.Find(x => x.WordOrPhrase == word);
}
...but I'm still a newbie when it comes to Python, so any help would be appreciated. Here is what I have so far:
When it comes to the FindWord() method, it could be rewritten as following:
def FindWord(word):
for x in words:
if x.WordOrPhrase == word:
return x
or
def FindWord(word):
return next((x for x in words if x.WordOrPhrase == word), None)
or
def FindWord(word):
return next(filter(lambda x: x.WordOrPhrase == word, words), None)
...but I'm struggling to rewrite Remove() method. Here is one way:
def remove_item(self):
word = self.listBox.get(ACTIVE)
new_word_list = [] # initialize empty list
delete_idxs = []
for idx, item in enumerate(self.words):
if item.wordorphrase == word:
delete_idxs.append(idx)
else:
new_word_list.append(item)
self.words = new_word_list # overwrite the old word_list with the new one
for idx in reversed(delete_idxs):
self.listBox.delete(idx)
...what I would like most is converting my C# method to Python. Here is what I have so far:
def remove_item(self):
word = Word()
try:
word = find_word(self.listBox.curselection())
except:
return
if self.listBox.len(curselection()) > 0:
try:
for item in self.listBox.curselection():
self.words.remove(lambda x: x.wordorphrase == item.text)
# listView1.Items[listView1.Items.Count - 1].Selected = true;
self.listBox.remove(item)
except:
pass
self.clear_all()
else:
pass
# show messagebox
I don't know how to access:
listView1.SelectedItems[0].Text
listView1.SelectedItems.Count > 0
listView1.SelectedItems
listView1.Items[listView1.Items.Count - 1].Selected
Here is what I have done so far:
# Vocabulary.py
# GUI program to manage unknown words
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import xml.etree.ElementTree as ET
import os
class Word:
def __init__(self, wordorphrase, explanation, translation, example):
self.wordorphrase = wordorphrase
self.explanation = explanation
self.example = example
self.translation = translation
class Vocabulary(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master = master
self.master.resizable(width = False, height = False)
self.master.title("Vocabulary")
self.create_widgets()
self.words = []
self.load_words()
def on_closing(self):
self.save_all()
if messagebox.askokcancel("Quit", "Do you want to quit?"):
self.master.destroy()
def create_widgets(self):
self.buttons_frame = Frame(self.master)
self.buttons_frame.grid(row = 10, sticky = W)
self.search_frame = Frame(self.master)
self.search_frame.grid(row = 1, sticky = W, columnspan = 2)
self.comboBox = ttk.Combobox(self.search_frame,
width = 3)
self.comboBox.grid(row = 0, column = 14, sticky = W)
self.comboBox['values'] = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' )
self.btn_Add = Button(self.buttons_frame,
text = 'Add',
command = self.add_item)
self.btn_Add.grid(row = 0, sticky = W)
self.btn_Remove = Button(self.buttons_frame,
text = 'Remove',
command = self.remove_item)
self.btn_Remove.grid(row = 0, column = 1, sticky = W)
self.btn_Edit = Button(self.buttons_frame,
text = 'Edit',
command = self.edit_item)
self.btn_Edit.grid(row = 0, column = 2, sticky = W)
self.btn_Save = Button(self.buttons_frame,
text = 'Save',
command = self.save_item)
self.btn_Save.grid(row = 0, column = 3, sticky = W)
self.btn_Refresh = Button(self.buttons_frame,
text = 'Refresh',
command = self.refresh_all)
self.btn_Refresh.grid(row = 0, column = 4, sticky = W)
self.lblSearch = Label(self.search_frame, text = 'SEARCH: ')
self.lblSearch.grid(row = 0, column = 5, sticky = W)
self.txt_Search = Text(self.search_frame,
height = 1,
width = 70)
self.txt_Search.grid(row = 0, column = 6, columnspan = 3, sticky = W)
self.lblWordsOrPhrases = Label(self.master, text = 'WORDS/PHRASES:')
self.lblWordsOrPhrases.grid(row = 2, column = 0)
self.lblWordOrPhrase = Label(self.master, text = 'Word or phrase:')
self.lblWordOrPhrase.grid(row = 2, column = 1, sticky = W)
self.listBox = Listbox(self.master,
selectmode='extended',
height = 34,
width = 38)
self.listBox.grid(row = 3, column = 0, rowspan = 7, sticky = W)
self.txt_WordOrPhrase = Text(self.master,
height = 1,
width = 40)
self.txt_WordOrPhrase.grid(row = 3, column = 1, sticky = N)
self.lblExplanation = Label(self.master, text = 'Explanation:')
self.lblExplanation.grid(row = 4, column = 1, sticky = W)
self.txt_Explanation = Text(self.master,
height = 10,
width = 40)
self.txt_Explanation.grid(row = 5, column = 1, sticky = N)
self.lblTranslation = Label(self.master, text = 'Translation:')
self.lblTranslation.grid(row = 6, column = 1, sticky = W)
self.txt_Translation = Text(self.master,
height = 10,
width = 40)
self.txt_Translation.grid(row = 7, column = 1, sticky = N)
self.lblExamples = Label(self.master, text = 'Example(s):')
self.lblExamples.grid(row = 8, column = 1, sticky = W)
self.txt_Example = Text(self.master,
height = 10,
width = 40)
self.txt_Example.grid(row = 9, column = 1, sticky = S)
def load_words(self):
self.listBox.delete(0, END)
self.words.clear()
path = os.path.expanduser('~/Desktop')
vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml')
if not os.path.exists(vocabulary):
if not os.path.exists(os.path.dirname(vocabulary)):
os.mkdir(os.path.dirname(vocabulary))
doc = ET.Element('Words')
tree = ET.ElementTree(doc)
tree.write(vocabulary)
else:
tree = ET.ElementTree(file=vocabulary)
for node in tree.findall('WordOrPhrase'):
w = Word(node.find('Word').text, node.find('Explanation').text, node.find('Translation').text,
node.find('Examples').text)
self.words.append(w)
self.listBox.insert(END, w.wordorphrase)
def save_all(self):
path = os.path.expanduser('~/Desktop')
vocabulary = os.path.join(path, 'Vocabulary', 'Words.xml')
tree = ET.ElementTree(file=vocabulary)
for xNode in tree.getroot().findall('WordOrPhrase'):
tree.getroot().remove(xNode)
for w in self.words:
xTop = ET.Element('WordOrPhrase')
xWord = ET.Element('Word')
xExplanation = ET.Element('Explanation')
xTranslation = ET.Element('Translation')
xExamples = ET.Element('Examples')
xWord.text = w.wordorphrase
xExplanation.text = w.explanation
xTranslation.text = w.translation
xExamples.text = w.example
xTop.append(xWord)
xTop.append(xExplanation)
xTop.append(xTranslation)
xTop.append(xExamples)
tree.getroot().append(xTop)
tree.write(vocabulary)
def add_item(self):
w = Word(self.get_word(), self.get_explanation(), self.get_translation(), self.get_example())
self.words.append(w)
self.listBox.insert(END, w.wordorphrase)
self.clear_all()
self.save_all()
def remove_item(self):
word = Word()
try:
word = find_word(self.listBox.curselection())
except:
return
if self.listBox.len(curselection()) > 0:
try:
for item in self.listBox.curselection():
self.words.remove(lambda x: x.wordorphrase == item.text)
# listView1.Items[listView1.Items.Count - 1].Selected = true;
self.listBox.remove(item)
except:
pass
self.clear_all()
else:
pass
# show messagebox
def edit_item(self):
pass
def save_item(self):
pass
def clear_all(self):
self.txt_WordOrPhrase.delete('1.0', END)
self.txt_Explanation.delete('1.0', END)
self.txt_Translation.delete('1.0', END)
self.txt_Example.delete('1.0', END)
def refresh_all(self):
pass
def get_word(self):
return self.txt_WordOrPhrase.get('1.0', '1.0 lineend')
def get_explanation(self):
return self.txt_Explanation.get('1.0', '1.0 lineend')
def get_translation(self):
return self.txt_Translation.get('1.0', '1.0 lineend')
def get_example(self):
return self.txt_Example.get('1.0', '1.0 lineend')
def find_word(word):
for x in self.words:
if x.wordorphrase == word:
return x
def main():
root = Tk()
gui = Vocabulary(root)
root.protocol('WM_DELETE_WINDOW', gui.on_closing)
root.mainloop()
if __name__ == '__main__':
main()
For my listboxes, I generally have the mode set to EXTENDED so that users can select one or more items and remove all at once. I do so via the following method:
# Function with Tk.Listbox passed as arg
def remove_from(list_box):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# Initialize a 'repositioning' variable
pos = 0
for item in selected_items:
# Set index of each item selected
idx = int(item) - pos
# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Increments to account for shifts
pos += 1
For example, lets say in my listbox I had 4 items. I then select the first item and the third item. By calling list_box.curselection() I've received the following:
selected_items = (0, 2)
Where 0 is the first item's position in the listbox, and 2 is the third item's position. Then for each item in my tuple, I establish its index.
Walking through this, for the first item the following takes place:
idx = 0 - 0
list_box.delete(0, 0)
pos = 1
So now I have deleted the item at position 0 (e.g. the first item) and my listbox has shifted! So the second is now the first, third is the second and fourth is the third. However, my tuple has not changed as it was the positions in the listbox of the original selection. This is key. What happens next is:
idx = 2 - 1
list_box.delete(1, 1)
pos = 2
Since the listbox shifted, position 1 now corresponds to the item that was originally in the third position of the listbox. This can continue for n positions.
For self.words removal
You could try the following:
# Function with Tk.Listbox and self.words[] passed as args
def remove_from(list_box, list):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# List of Words already constructed
word_list = list
# Initialize a 'repositioning' variable
pos = 0
for item in selected_items:
# Set index of each item selected
idx = int(item) - pos
# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Gets the string value of the given index
word = list_box.get(idx, idx)
# Removes the word from the list
if any(word in x for x in word_list):
word_list.remove(word)
# Increments to account for shifts
pos += 1
I've got the following code in my Excel DNA plugin
In my AutoOpen method I put the following code:
ExcelIntegration.RegisterUnhandledExceptionHandler(ex => ex.ToString());
I've got the following function that gets called from my excel sheet.
[ExcelFunction(Category = "Foo", Description = "Sets value of cell")]
public static Foo(String idx)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Workbook wb = app.Workbooks[1];
Excel.Worksheet ws = GetSheet("Main");
// This gives us the row
Excel.Name idxRange = wb.Names.Item("COL_Main_Index");
var row = (int)app.WorksheetFunction.Match(idx, idxRange.RefersToRange, 0);
// Get the Column
Excel.Name buyOrderRange = wb.Names.Item("COL_Main_BuyOrder");
var col = (int)buyOrderRange.RefersToRange.Cells.Column;
// create the range and update it
Excel.Range r = (Excel.Range)ws.Cells[row, col];
r.Value ="Foo";
}
The issue is that I can't actually set any cell values. When I call the method it causes an error on the last line.
My error handler gives me the followign error:
{System.Runtime.InteropServices.COMException (0x800A03EC)
I've also tried to set the cell value like so:
r = (Excel.Range)ws.Cells[12, 22];
const int nCells = 1;
Object[] args1 = new Object[1];
args1[0] = nCells;
r.GetType().InvokeMember("Value2", BindingFlags.SetProperty, null, r, args1);
With the same result.
Can anyone point to what I might be doing wrong here?
Actually, you can write in any cell if you do this in an async job as a macro.
Simple Example:
using ExcelDna.Integration;
using Excel = Microsoft.Office.Interop.Excel;
[ExcelFunction(Category = "Foo", Description = "Sets value of cell")]
public static Foo(String idx)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Range range = app.ActiveCell;
object[2,2] dummyData = new object[2, 2] {
{ "foo", "bar" },
{ 2500, 7500 }
};
var reference = new ExcelReference(
range.Row, range.Row + 2 - 1, // from-to-Row
range.Column - 1, range.Column + 2 - 1); // from-to-Column
// Cells are written via this async task
ExcelAsyncUtil.QueueAsMacro(() => { reference.SetValue(dummyData); });
// Value displayed in the current cell.
// It still is a UDF and can be executed multiple times via F2, Return.
return "=Foo()";
}
Writing into a single Cell:
int row = 5;
int column = 6;
var reference = new ExcelReference(row - 1, column - 1);
ExcelAsyncUtil.QueueAsMacro(() => { reference.SetValue("Foobar"); });
// edit:
just fyi, you can also use:
private void WriteArray(object[,] data)
{
Excel.Application app = (Excel.Application)ExcelDnaUtil.Application;
Excel.Worksheet worksheet= (Excel.Worksheet)app.ActiveWorkbook.ActiveSheet;
Excel.Range startCell = app.ActiveCell;
Excel.Range endCell = (Excel.Range)worksheet.Cells[startCell.Row + data.GetLength(0) - 1, startCell.Column + data.GetLength(1) - 1];
var writeRange = worksheet.Range[startCell, endCell];
writeRange.Value2 = data;
}
And then:
object[,] data = ...;
ExcelAsyncUtil.QueueAsMacro(() =>
{
WriteArray();
});
Excel does not allow you to set other worksheet cells from within a user-defined worksheet function. This is to preserve the dependency tree Excel uses to manage the recalculation. This is true whether you are using VBA, the C API or Excel-DNA.
Best is to add a ribbon button, context menu or shortcut key to effect the changes via a macro.
There are some ugly workarounds, but I would not recommend it.
Here is the answer using .NET VB
Dim row As Integer = 7
Dim column As Integer = 7
Dim reference = New ExcelReference(row, column)
ExcelAsyncUtil.QueueAsMacro(Sub()
reference.SetValue("Test")
End Sub)
I have the following code which is supposed to add a bulleted list to a word document that I'm generating automatically. From other answers I believe the code is correct, but the result doesn't produce any bullet points at all, it doesn't seem to apply the indent either.
Any Ideas?
Microsoft.Office.Interop.Word.Paragraph assets;
assets = doc.Content.Paragraphs.Add(Type.Missing);
// Some code to generate the text
foreach (String asset in assetsList)
{
assetText = assetText + asset + "\n";
}
assets.Range.ListFormat.ApplyBulletDefault(Type.Missing);
// Add it to the document
assets.Range.ParagraphFormat.LeftIndent = -1;
assets.Range.Text = assetText;
assets.Range.InsertParagraphAfter();
This happens because you're adding multiple paragraphs to the range after the range (it seems that setting the Text property is equivalent to InsertAfter). You want to InsertBefore the range so that the formatting you set gets applied.
Paragraph assets = doc.Content.Paragraphs.Add();
assets.Range.ListFormat.ApplyBulletDefault();
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < bulletItems.Length - 1)
bulletItem = bulletItem + "\n";
assets.Range.InsertBefore(bulletItem);
}
Notice that we add an End of Paragraph mark to all items except the last one. You will get an empty bullet if you add one to the last.
This is based on Tergiver's answer. The difference is it inserts the list items in the correct order after the initially created paragraph. For your own use make the starting range equal to the item you want to insert the list after.
Paragraph assets = doc.Content.Paragraphs.Add();
rng = assets.Range;
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
object listType = 0;
rng.ListFormat.ApplyBulletDefault(ref listType);
string[] bulletItems = new string[] { "One", "Two", "Three" };
for (int i = 0; i < bulletItems.Length; i++)
{
string bulletItem = bulletItems[i];
if (i < RowCount - 1)
bulletItem = bulletItem + "\n";
rng.InsertAfter(bulletItem);
}
Please note I don't really understand what I'm doing with the range here. This solution was arrived at after considerable trial and error. I suspect it may have to do with the fact that I'm reusing the same range and Tergiver's solution is grabbing a new range each time the range is accessed. I particularly don't understand the following lines:
rng.InsertAfter("\n");
start = rng.End;
end = rng.End;
rng = _oDoc.Range(ref start, ref end);
Generally any alterations to the above code and the list gets intermingled with the previous element. If somebody could explain why this works, I'd be grateful.
You can try below code block if you want list-sublist relations:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
Attention this point: If you don't know input length, you must not define the end of range value like this:
static void Main(string[] args)
{
try
{
Application app = new Application();
Document doc = app.Documents.Add();
Range range = doc.Range(0, 0);
range.ListFormat.ApplyNumberDefault();
range.Text = "Birinci";
range.InsertParagraphAfter();
ListTemplate listTemplate = range.ListFormat.ListTemplate;
//range.InsertAfter("Birinci");
//range.InsertParagraphAfter();
//range.InsertAfter("İkinci");
//range.InsertParagraphAfter();
//range.InsertAfter("Üçüncü");
//range.InsertParagraphAfter();
Range subRange = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
subRange.ListFormat.ApplyBulletDefault();
subRange.ListFormat.ListIndent();
subRange.Text = "Alt Birinci";
subRange.InsertParagraphAfter();
ListTemplate sublistTemplate = subRange.ListFormat.ListTemplate;
Range subRange2 = doc.Range(subRange.StoryLength - 1, range.StoryLength - 1);
subRange2.ListFormat.ApplyListTemplate(sublistTemplate);
subRange2.ListFormat.ListIndent();
subRange2.Text = "Alt İkinci";
subRange2.InsertParagraphAfter();
Range range2 = doc.Range(range.StoryLength - 1, range.StoryLength - 1);
range2.ListFormat.ApplyListTemplateWithLevel(listTemplate,true);
WdContinue isContinue = range2.ListFormat.CanContinuePreviousList(listTemplate);
range2.Text = "İkinci";
range2.InsertParagraphAfter();
Range range3 = doc.Range(range2.StoryLength - 1, range.StoryLength - 1);
range3.ListFormat.ApplyListTemplate(listTemplate);
range3.Text = "Üçüncü";
range3.InsertParagraphAfter();
string path = Environment.CurrentDirectory;
int totalExistDocx = Directory.GetFiles(path, "test*.docx").Count();
path = Path.Combine(path, string.Format("test{0}.docx", totalExistDocx + 1));
app.ActiveDocument.SaveAs2(path, WdSaveFormat.wdFormatXMLDocument);
doc.Close();
Process.Start(path);
}
catch (Exception exception)
{
throw;
}
}
You just need to keep track of the start and end positions of the list and then apply the list format.
Application wordApp = new Application() {
Visible = true
};
Document doc = wordApp.Documents.Add();
Range range = doc.Content;
range.Text = "Hello world!";
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
// start of list
int startOfList = range.Start;
// each \n character adds a new paragraph...
range.Text = "Item 1\nItem 2\nItem 3";
// ...or insert a new paragraph...
range.InsertParagraphAfter();
range = doc.Paragraphs.Last.Range;
range.Text = "Item 4\nItem 5";
// end of list
int endOfList = range.End;
// insert the next paragraph before applying the format, otherwise
// the format will be copied to the suceeding paragraphs.
range.InsertParagraphAfter();
// apply list format
Range listRange = doc.Range(startOfList, endOfList);
listRange.ListFormat.ApplyBulletDefault();
range = doc.Paragraphs.Last.Range;
range.Text = "Bye for now!";
range.InsertParagraphAfter();