Fix the cell width in Word using Open XML SDK - openxml

I have a table with one row in a docx file and I want to add some rows. For the first existing row I set the GridSpan to 3. In the next one I want add a row only with two cell, then I have the result as on the picture. How can I fix the new row width to the table width? The same I want to do, when I add only a one cell in the new row.
My code:
private static TableRow AddRow(WordprocessingDocument docx, Table tbl, int cellsQuantity)
{
TableRow newRow = new TableRow();
var firstCell = tbl.Descendants<TableRow>().First()
.Descendants<TableCell>().First();
firstCell.Append(new TableCellProperties(new GridSpan() { Val = 3 }));
for (int i = 0, max = cellsQuantity; i < max; i++)
{
// TableCellProperties tcp = new TableCellProperties(new TableCellWidth() { Width = firstCell.TableCellProperties.TableCellWidth.Width, Type = firstCell.TableCellProperties.TableCellWidth.Type });
TableCell cell = new TableCell(new Paragraph(new Run(new Text("test"))));
newRow.AppendChild(cell);
}
tbl.Append(newRow);
return newRow;
}

Ok, I thing I got it :)
private static TableRow AddRow(WordprocessingDocument docx, Table tbl, int cellsQuantity)
{
TableRow newRow = new TableRow();
var grid = tbl.Descendants<TableGrid>().First();
var firstCell = tbl.Descendants<TableRow>().First()
.Descendants<TableCell>().First();
firstCell.Append(new TableCellProperties(new GridSpan() { Val = 4 }));
int ind = 0;
int[] widthPerColumn = new int[] { 3070, 1536, 1535, 3071 };
grid.Descendants<GridColumn>().ToList().ForEach(x =>
{
x.Width = widthPerColumn[ind++].ToString();
});
int[] gridSpan = null;
switch (cellsQuantity)
{
case 4:
gridSpan = new int[] { 1, 1, 1, 1 };
break;
case 3:
gridSpan = new int[] { 1, 2, 1 };
break;
case 2:
gridSpan = new int[] { 2, 2 };
break;
case 1:
gridSpan = new int[] { 4 };
break;
default:
throw new InvalidOperationException("The cellsQuantity variable must have a value from [1,4] range");
}
for (int i = 0, max = cellsQuantity; i < max; i++)
{
TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = gridSpan[i] });
TableCell cell = new TableCell(tcp, new Paragraph(new Run(new Text("test"))));
newRow.AppendChild(cell);
}
tbl.Append(newRow);
return newRow;
}

TableCell tCell = new TableCell();
tCell.Append(new TableCellProperties(
new GridSpan { Val = table.LastChild.ChildElements.Count },
new Justification { Val = JustificationValues.Right })
);

Related

DOCX4J conditional paragaph update merge FieldUpdater Does not work

Using a legacy IF field code:
enter image description here
and content controls:
private static byte[] mergingDocxFileWithXml(File file, File fileXml) {WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(file)
MainDocumentPart mainDocumentPart = wordMLPackage.getMainDocumentPart()
ArrayList<String> datas
List<Object> contentControls = ContentControl.getAllContentControl(mainDocumentPart)
List<String> arrayListXpathToBoucle = new ArrayList<>()
for (Object contenControl : contentControls) {
ContentControl cControl = new ContentControl(contenControl)
String xPath = cControl.getXPath()
String title = cControl.getTitle()
if (xPath != null) {
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
}
switch (title) {
case "DateDuJour":
cControl.setValue(getDateDay())
break
case "checkbox":
String checkValue = new String(Character.toChars(0x2612))
if (datas[0] != "1") {
checkValue = new String(Character.toChars(0x2610))
}
cControl.setValue(checkValue)
break
case "Boucle_Ligne":
xPath = cControl.getTag()
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int totalNode = nodeList.getLength()
for (int j = 0; j < totalNode; j++) {
wordMLPackage = mapingDataNode(j, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, null, 0)
}
wordMLPackage.mainDocumentPart.getContent().remove(indexBoucleContent)
break;
case "Boucle_Colonne":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
String boucleValue = ""
for (int i = 0; i < totalNode; i++) {
datas = XmlPath.getXmlDataFrom(fileXml, dataXpath.get(0))
boucleValue += datas.get(i) + ", "
}
boucleValue = boucleValue.substring(0, boucleValue.length() - 2)
addValueInContentControl(contentControls, dataXpath.get(0), 0, boucleValue, null, wordMLPackage)
break
case "Boucle_Ligne_Table":
xPath = cControl.getTag()
NodeList nodeList = XmlPath.getNodeListXmlFile(fileXml, xPath)
int indexBoucleContent = getIndexContentBoucle(wordMLPackage.mainDocumentPart.getContent(), xPath)
List<String> dataXpath = getAllXpathForBoucle(contentControls, xPath)
int totalNode = nodeList.getLength()
for (int i = 0; i < dataXpath.stream().count(); i++) {
arrayListXpathToBoucle.add(dataXpath.get(i))
}
int nodeIndex = 0
Tbl arraysBoucle = getArraysBoucle(wordMLPackage, indexBoucleContent)
Tr trContent
for (int i = 0; i < totalNode; i++) {
nodeIndex = i + 1
if (arraysBoucle.getContent().stream().count() > 1) {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(1))
} else {
trContent = WoeDocx4jFunction.getTr(arraysBoucle.getContent().get(0))
}
wordMLPackage = mapingDataNode(i, cControl, contentControls, fileXml, dataXpath, wordMLPackage, indexBoucleContent, trContent, nodeIndex)
}
int lastIndexTr = wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.stream().count()
wordMLPackage.getMainDocumentPart().getContent().get(indexBoucleContent).sdtContent.content.get(1).value.content.remove(lastIndexTr - 1)
break
case "IMAGE":
datas = XmlPath.getXmlDataFrom(fileXml, xPath)
byte[] imageByte = base64ToImage(datas.get(0))
Inline inlineImage = newImage(wordMLPackage, imageByte)
cControl.setValue(null, inlineImage)
break
default:
String xpathBoucle = arrayListXpathToBoucle.find { it.startsWith(xPath) }
if (xpathBoucle != xPath) {
addValueInContentControl(contentControls, xPath, 0, "", fileXml,wordMLPackage)
}
break
}
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
wordMLPackage= mergingFieldWordMlPackage(wordMLPackage)
FieldUpdater updater = new FieldUpdater(wordMLPackage)
updater.update(true);
wordMLPackage.save(outputStream);
return outputStream.toByteArray();
}
Docx4j's legacy field processing does not parse IF fields: http://webapp.docx4java.org/OnlineDemo/ecma376/WordML/IF.html
If you need to do that, you'll need to write code to do the parsing.
An alternative would be to use OpenDoPE conditional content controls. With one of these, the content of the SDT is included only if the associated XPath evaluates to true.

Vehicle routing problem with dependent dimension constraints (Google ORTools)

I'm very new to OR-Tools and I'm trying to solve a modified VRP with capacity constraints from Google's guide.
In my problem vehicles transport multiple types of items. Some types can be transported together and others cannot.
What I tried
In the following code the types are A and B (they should not be transported together).
First I defined the two callbacks for demands and added the dimensions to the routing model
int demandACallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => {
var fromNode = manager.IndexToNode(fromIndex);
return demandsA[fromNode];
});
int demandBCallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => {
var fromNode = manager.IndexToNode(fromIndex);
return demandsB[fromNode];
});
routing.AddDimensionWithVehicleCapacity(demandACallbackIndex, 0,
capacitiesA,
true,
"CapacityA");
routing.AddDimensionWithVehicleCapacity(demandBCallbackIndex, 0,
capacitiesB,
true,
"CapacityB");
Then I retrieved the dimensions and added constraints to routing.solver() for every node
var capacityADimension = routing.GetDimensionOrDie("CapacityA");
var capacityBDimension = routing.GetDimensionOrDie("CapacityB");
for (int i = 0; i < noDeliveries; i++) {
var index = manager.NodeToIndex(i);
routing.solver().Add(capacityADimension.CumulVar(index) * capacityBDimension.CumulVar(index) == 0);
}
When I run the solver (with two vehicles) these constraints seem to be ignored (one vehicle remains parked while the other does all the work even though it shouldn't transport both types of items).
Is this even possible with OR-Tools? If yes, what did I do wrong?
Full code
public SimpleVehicleRoutingSolutionDto SolveVehicleRoutingWithItemConstraints(long[,] distances, long[] capacitiesA, long[] capacitiesB, long[] demandsA, long[] demandsB, int depot)
{
int noVehicles = capacitiesA.Length;
int noDeliveries = deliveriesA.Length;
RoutingIndexManager manager =
new RoutingIndexManager(noDeliveries, noVehicles, depot);
RoutingModel routing = new RoutingModel(manager);
int transitCallbackIndex = routing.RegisterTransitCallback((long fromIndex, long toIndex) => {
var fromNode = manager.IndexToNode(fromIndex);
var toNode = manager.IndexToNode(toIndex);
return distances[fromNode, toNode];
});
routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
int demandACallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => {
// Convert from routing variable Index to demand NodeIndex.
var fromNode = manager.IndexToNode(fromIndex);
return demandsA[fromNode];
});
int demandBCallbackIndex = routing.RegisterUnaryTransitCallback((long fromIndex) => {
// Convert from routing variable Index to demand NodeIndex.
var fromNode = manager.IndexToNode(fromIndex);
return demandsB[fromNode];
});
routing.AddDimensionWithVehicleCapacity(demandACallbackIndex, 0,
capacitiesA,
true,
"CapacityA");
routing.AddDimensionWithVehicleCapacity(demandBCallbackIndex, 0,
capacitiesB,
true,
"CapacityB");
var capacityADimension = routing.GetDimensionOrDie("CapacityA");
var capacityBDimension = routing.GetDimensionOrDie("CapacityB");
for (int i = 0; i < noDeliveries; i++) {
var index = manager.NodeToIndex(i);
routing.solver().Add(capacityADimension.CumulVar(index) * capacityBDimension.CumulVar(index) == 0);
}
RoutingSearchParameters searchParameters =
operations_research_constraint_solver.DefaultRoutingSearchParameters();
searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc;
searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch;
searchParameters.TimeLimit = new Duration { Seconds = 1 };
Assignment solution = routing.SolveWithParameters(searchParameters);
var ret = new SimpleVehicleRoutingSolutionDto();
long totalDistance = 0;
for (int i = 0; i < noVehicles; ++i)
{
var vecihle = new VehiclePathDto { Index = i };
long routeDistance = 0;
var index = routing.Start(i);
while (routing.IsEnd(index) == false)
{
long nodeIndex = manager.IndexToNode(index);
vecihle.Waypoints.Add(new WaypointDto { Index = nodeIndex });
var previousIndex = index;
index = solution.Value(routing.NextVar(index));
routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0);
}
vecihle.Distance = routeDistance;
ret.Vehicles.Add(vecihle);
totalDistance += routeDistance;
}
ret.TotalDistance = totalDistance;
return ret;
}
And the input:
long[,] dist = {
{ 0, 5, 6 },
{ 5, 0, 3 },
{ 6, 3, 0 }
};
long[] capA = { 5, 5 };
long[] capB = { 5, 5 };
long[] demA = { 0, 1, 0 };
long[] demB = { 0, 0, 1 };
var routingSolution = vehicleRouting.SolveVehicleRoutingWithItemConstraints(dist, capA, capB, demA, demB, 0);
I fixed the problem.
The issue was that the number of nodes was 3 (noDeliveries), however the number of indices was 6, so I only set the constraint on half of them.
Fixed code:
for (int i = 0; i < manager.GetNumberOfIndices(); i++) {
routing.solver().Add(capacityADimension.CumulVar(i) * capacityBDimension.CumulVar(i) == 0);
}
EDIT:
Even better if constraints are set only for the route end node, since the CumulVar value is strictly increasing.
for (int j = 0; j < noVehicles; j++) {
var index = routing.End(j);
routing.solver().Add(capacityADimension.CumulVar(index) * capacityBDimension.CumulVar(index) == 0);
}

OpenXML / Xceed insert Table without empty lines

I have an existing.docx document with some text. All I want is to insert programmatically a table to a specific place. So my idea was to add a Keyword where the table should be inserted. There are no empty lines, before and after the keyword.
After the insertion of the table I add \n, before and after the table, for an empty line but somehow the Xceed library adds three after the table and two before the table.
Here is how I'm doing it:
using (DocX document = DocX.Load(#"C:\Users\rk\Desktop\test.docx"))
{
var IntTableSoftwareLocation = document.FindAll("Table").FirstOrDefault();
document.ReplaceText("Table", "");
var tableSoftware = document.InsertTable(IntTableSoftwareLocation, 3, 5);
tableSoftware.InsertParagraphBeforeSelf("\n");
tableSoftware.InsertParagraphAfterSelf("\n");
tableSoftware.SetBorder(TableBorderType.InsideH, new Border());
tableSoftware.SetBorder(TableBorderType.InsideV, new Border());
tableSoftware.SetBorder(TableBorderType.Left, new Border());
tableSoftware.SetBorder(TableBorderType.Bottom, new Border());
tableSoftware.SetBorder(TableBorderType.Top, new Border());
tableSoftware.SetBorder(TableBorderType.Right, new Border());
//Header
tableSoftware.Rows[0].Cells[0].Paragraphs[0].Append("Col1").Bold().Font("Arial").FontSize(11d);
tableSoftware.Rows[0].Cells[1].Paragraphs[0].Append("Col2").Bold().Font("Arial").FontSize(11d);
tableSoftware.Rows[0].Cells[2].Paragraphs[0].Append("Col3").Bold().Font("Arial").FontSize(11d);
tableSoftware.Rows[0].Cells[3].Paragraphs[0].Append("Col4.").Bold().Font("Arial").FontSize(11d);
tableSoftware.Rows[0].Cells[4].Paragraphs[0].Append("Col5").Bold().Font("Arial").FontSize(11d);
//Content
string TextToInsert = "Some Text";
//Column width
for (int i = 0; i < tableSoftware.RowCount; i++)
{
for (int x = 0; x < tableSoftware.ColumnCount; x++)
{
#region set column width
if (x == 0)
{
tableSoftware.Rows[i].Cells[x].Width = 28.3; // 1cm
}
else if (x == 1)
{
tableSoftware.Rows[i].Cells[x].Width = 318;
}
else if (x == 2)
{
tableSoftware.Rows[i].Cells[x].Width = 50;
}
else if (x == 3)
{
tableSoftware.Rows[i].Cells[x].Width = 28.3;
}
else if (x == 4)
{
tableSoftware.Rows[i].Cells[x].Width = 64;
}
#endregion
}
}
tableSoftware.Rows[2].Cells[1].Paragraphs[0].Append(TextToInsert + "\n").FontSize(11d).Bold().Font("Arial");
tableSoftware.Rows[2].Cells[2].Paragraphs[0].Append("User").Font("Arial").Alignment = Alignment.center;
tableSoftware.Rows[2].Cells[2].VerticalAlignment = VerticalAlignment.Center;
tableSoftware.Rows[2].Cells[3].Paragraphs[0].Append("1").Font("Arial").Alignment = Alignment.center;
tableSoftware.Rows[2].Cells[3].VerticalAlignment = VerticalAlignment.Center;
tableSoftware.Rows[2].Cells[4].Paragraphs[0].Append("2.199,00 €").Font("Arial").Alignment = Alignment.right;
tableSoftware.Rows[2].Cells[4].VerticalAlignment = VerticalAlignment.Center;
document.Save();
}
And thats how my docx Document looks like:
laksjdf
Table
alskdfjs
Ok, this is how it should be done:
//Find the Paragraph by keyword
var paraTable = document.Paragraphs.FirstOrDefault(x => x.Text.Contains("Table"));
// Remove the Keyword
paraTable.RemoveText(0);
//Insert the table into Paragraph
var table = paraTable.InsertTableAfterSelf(3, 5);
No strange empty lines anymore

inserting into SQL via sqlbulk

hallo i have this sniped code like this:
public static void Put_CSVtoSQL_Adhesion()
{
bool IsFirst = true;
DataTable dt = new DataTable();
string line = null;
int i = 0;
try
{
string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);
using (StreamReader sr = File.OpenText(fileName))
{
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(';');
if (data.Length > 0)
{
if (i == 0)
{
foreach (var item in data)
{
dt.Columns.Add(new DataColumn());
}
i++;
}
DataRow row = dt.NewRow();
row.ItemArray = data;
// Pour enlever la tete
if (!IsFirst) dt.Rows.Add(row);
IsFirst = false;
}
}
}
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
{
int CountColl = dt.Columns.Count;
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
copy.DestinationTableName = "cotisation";
copy.WriteToServer(dt);
}
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message);
}
}
this code work well, but now i have more than 60 column, should i type manualy from 1 to 60 column or there are another methode ?
copy.ColumnMappings.Add(0, 1);
copy.ColumnMappings.Add(1, 2);
copy.ColumnMappings.Add(2, 3);
copy.ColumnMappings.Add(3, 4);
copy.ColumnMappings.Add(4, 5);
...until 60 column ?
the column is all the same i just shifted 1 column, because the first one is autoincremented column as an ID
Write a loop?
for (int i = 0; i < dt.Columns.Count - 1; i++)
{
copy.ColumnMappings.Add(i, i + 1);
}

Change label's text with using property

I am working on my C# ADO.NET app. I have connected my SQL Server database with C# app, and I can perform simple CRUD operations. I want to make that my app open my reminder form when someone in my database have birthday, so I made my query and all persons who have birthday on today's day are in my query, and with using property from my reminder form I change label's text with name and surname of person who have birthday. Now I just dont know how to change next label's text when more than one person have birthday in my query... I dont know how to get next element in my foreach loop...
Here is my code:
Form2 forma = new Form2();
TBirthDayEntities today_born = new TBirthDayEntities();
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Enabled = true;
timer1.Start();
}
private Boolean provjera_rodj()
{
Boolean flag = false;
int cnt = 0;
IQueryable<TBD> query;
using (var data = new TBirthDayEntities())
{
query = (from x in data.TBD
where x.BirthDay.Day == System.DateTime.Now.Day && x.BirthDay.Month == System.DateTime.Now.Month
select x);
foreach (var x in query)
{
today_born.TBD.Add(x);
cnt += 1;
flag = true;
}
}
switch (cnt)
{
case 1:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + " " + x.LName;
}
break;
}
case 2:
{
foreach (var x in today_born.TBD)
{
forma.p_label2 = x.FName + x.LName;
forma.p_label3 = x.FName + x.LName; //wrong
}
break;
}
}
return flag;
}
private void timer1_Tick(object sender, EventArgs e)
{
Boolean flag = provjera_rodj();
if (flag == true)
{
forma.Show();
timer1.Stop();
}
}
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Label>()
{
forma.p_label2
, forma.p_label3
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x in today_born.TBD[i];
lstLabel[x].Text = x.FName + x.LName;
}
break;
}
}
EDIT:
switch (cnt)
{
case 1:
case 2:
{
var lstLabel = new List<Action<string>>()
{
new Action<string>(s =>forma.p_label2 = s)
, new Action<string>(s =>forma.p_label3 = s)
};
for(int i = 0; i < today_born.TBD.Count; i++)
{
var x = today_born.TBD[i];
lstLabel[x](x.FName + x.LName);
}
break;
}
}