I am trying to create a word table from xml file but the rows are not in their proper order,ie the first element occurs as last row, 2nd as 1st row and so on. Where am i going wrong?
Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, ds.Tables[0].Rows.Count, ds.Tables[0].Columns.Count, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
for (int r = 1; r <= ds.Tables[0].Rows.Count; r++)
{
for (int c = 1; c <= ds.Tables[0].Columns.Count; c++)
{
oTable.Cell(r, c).Range.Text = ds.Tables[0].Rows[r-1].ItemArray[c-1].ToString();
}
}
Here is the sample code to create simple word file with Table. It will give you a loop hint how to proceed with it.
class Program
{
static void Main(string[] args)
{
Document doc = new Document();
Section s = doc.AddSection();
Table table = s.AddTable(true);
//Create Header and Data
String[] header = { "Item", "Description", "Qty", "Unit Price", "Price" };
String[][] data = {
new String[]{ "Spire.Doc for .NET",".NET Word Component","1","$799.00","$799.00"},
new String[]{"Spire.XLS for .NET",".NET Excel Component","2","$799.00","$1,598.00"},
new String[]{"Spire.Office for .NET",".NET Office Component","1","$1,899.00","$1,899.00"},
new String[]{"Spire.PDF for .NET",".NET PDFComponent","2","$599.00","$1,198.00"},
};
//Add Cells
table.ResetCells(data.Length + 1, header.Length);
//Header Row
TableRow fRow = table.Rows[0];
fRow.IsHeader = true;
//Row Height
fRow.Height = 23;
//Header Format
fRow.RowFormat.BackColor = Color.AliceBlue;
for (int i = 0; i < header.Length; i++)
{
//Cell Alignment
Paragraph p = fRow.Cells[i].AddParagraph();
fRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
//Data Format
TextRange TR = p.AppendText(header[i]);
TR.CharacterFormat.FontName = "Calibri";
TR.CharacterFormat.FontSize = 14;
TR.CharacterFormat.TextColor = Color.Teal;
TR.CharacterFormat.Bold = true;
}
//Data Row
for (int r = 0; r < data.Length; r++)
{
TableRow dataRow = table.Rows[r + 1];
//Row Height
dataRow.Height = 20;
//C Represents Column.
for (int c = 0; c < data[r].Length; c++)
{
//Cell Alignment
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
//Fill Data in Rows
Paragraph p2 = dataRow.Cells[c].AddParagraph();
TextRange TR2 = p2.AppendText(data[r][c]);
//Format Cells
p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
TR2.CharacterFormat.FontName = "Calibri";
TR2.CharacterFormat.FontSize = 12;
TR2.CharacterFormat.TextColor = Color.Brown;
}
}
//Save and Launch
doc.SaveToFile("WordTable.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("WordTable.docx");
Console.ReadLine();
}
Related
I have created a flow document code-behind. I use a table with four columns.
But the fourth column didn't appear when printing
It seems that the pagewidth is just over half page
When I reduce columnwidth of columns - they appear but the text is wrapping
Here is the code I have
PrintDialog printDlg = new PrintDialog();
FlowDocument FlowTabledoc = new FlowDocument();
// FlowTabledoc.PageWidth = Double.NaN; dit not work
FlowTabledoc.PageWidth = printDlg.PrintableAreaWidth;
Table logflowtable = new Table();
FlowTabledoc.Blocks.Add(logflowtable);
logflowtable.CellSpacing = 5;
int numberOfColumns = 4;
for (int x = 0; x < numberOfColumns; x++)
{
logflowtable.Columns.Add(new TableColumn());
}
logflowtable.Columns[0].Width = new GridLength(60.0, GridUnitType.Pixel);
logflowtable.Columns[1].Width = new GridLength(120.0, GridUnitType.Pixel);
logflowtable.Columns[2].Width = new GridLength(190.0, GridUnitType.Pixel);
logflowtable.Columns[3].Width = new GridLength(90.0, GridUnitType.Pixel);
logflowtable.RowGroups.Add(new TableRowGroup());
int RowAnzahl = LogTB.Rows.Count;
int ColAnzahl = LogTB.Columns.Count;
Paragraph Abschnitt = new Paragraph();
Abschnitt.FontSize = 14;
for (int r = 0; r <= RowAnzahl - 1; r++)
{
logflowtable.RowGroups[0].Rows.Add(new TableRow());
currentRow = logflowtable.RowGroups[0].Rows[r+1];
for (int c = 0; c <= ColAnzahl - 1; c++)
{
currentRow.FontSize = 14;
currentRow.FontWeight = FontWeights.Normal;
currentRow.Cells.Add(new TableCell(new Paragraph(new Run(LogTB.Rows[r][c].ToString()))));
}
FlowTabledoc.Blocks.Add(Abschnitt);
}
FlowTabledoc.Name = "FlowDoc";
IDocumentPaginatorSource idpSource = FlowTabledoc;
printDlg.PrintDocument(idpSource.DocumentPaginator, "Title-Header");
}
}
Solution found:
FlowTabledoc.ColumnWidth = 793;
I'm using GemBox.Presentation and I'm creating a large table in my PPTX file. Similar to this example, e.g.:
PresentationDocument presentation = new PresentationDocument();
Slide slide = presentation.Slides.AddNew(SlideLayoutType.Custom);
int rowCount = 100;
int columnCount = 4;
int columnWidth = 5;
Table table = slide.Content.AddTable(1, 1, columnCount * columnWidth, 0, LengthUnit.Centimeter);
for (int i = 0; i < columnCount; i++)
table.Columns.AddNew(Length.From(5, LengthUnit.Centimeter));
for (int r = 0; r < rowCount; r++)
{
TableRow row = table.Rows.AddNew(0);
for (int c = 0; c < columnCount; c++)
{
TableCell cell = row.Cells.AddNew();
TextParagraph paragraph = cell.Text.AddParagraph();
TextRun run = paragraph.AddRun(string.Format("Cell {0}-{1}", r + 1, c + 1));
}
}
presentation.Save("output.pptx");
As expected, the table doesn't fit on the slide:
So I need to split this table into multiple tables or multiple slides so that each table fits on its slide and all rows are visible.
How can I do that?
How can I find if the new TableRow will exceed the Slide height?
If you have dynamic row heights (for instance, some cells may contain multiple lines of text), then you'll need to paginate the content.
For example, see the following:
table.Frame.FormatDrawing(new PaginatorOptions() { UpdateTableRowHeights = true });
DrawingLayout tableLayout = table.Frame.Layout;
double maxHeight = presentation.SlideSize.Height - tableLayout.Top;
double currentHeight = 0;
TableRowCollection sourceRows = table.Rows;
TableRowCollection newRows = null;
int currentRowIndex = 0;
// Split the main table into multiple new tables based on the row heights.
while (currentRowIndex < sourceRows.Count)
{
currentHeight += sourceRows[currentRowIndex].Height;
// Create new slide with new table.
if (currentHeight > maxHeight)
{
currentHeight = sourceRows[currentRowIndex].Height;
Slide newSlide = presentation.Slides.AddNew(SlideLayoutType.Blank);
Table newTable = newSlide.Content.AddTable(tableLayout.Left, tableLayout.Top, tableLayout.Width, 0);
foreach (var column in table.Columns)
newTable.Columns.AddClone(column);
newRows = newTable.Rows;
}
// Move row from the main table to a new table.
if (newRows != null)
{
newRows.AddClone(sourceRows[currentRowIndex]);
sourceRows.RemoveAt(currentRowIndex);
}
else
{
++currentRowIndex;
}
}
presentation.Save("output.pptx");
If you have constant row heights, like shown in your screenshot, then you can simplify this.
For example, like the following:
int rowsPerSlide = 16;
TableRowCollection rows = table.Rows;
DrawingLayout layout = table.Frame.Layout;
for (int t = 1, tablesCount = (int)Math.Ceiling(rows.Count / (double)rowsPerSlide); t < tablesCount; t++)
{
Slide newSlide = presentation.Slides.AddNew(SlideLayoutType.Blank);
Table newTable = newSlide.Content.AddTable(layout.Left, layout.Top, layout.Width, 0);
foreach (var column in table.Columns)
newTable.Columns.AddClone(column);
for (int r = rowsPerSlide, rowsCount = Math.Min(rowsPerSlide * 2, rows.Count); r < rowsCount; r++)
{
newTable.Rows.AddClone(rows[rowsPerSlide]);
rows.RemoveAt(rowsPerSlide);
}
}
presentation.Save("output.pptx");
How to create a new page on each new table?
It means that the table should be placed on one page.
The following code is a sample code that outputs login, but does not create a new page for each table.
List<System.Data.DataTable> bbb = new List<System.Data.DataTable>();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Columns 1");
dt.Columns.Add("Columns 2");
dt.Columns.Add("Columns 3");
dt.Rows.Add("aaa", "aaa", "aaa");
dt.Rows.Add("bbb", "bbb", "bbb");
dt.Rows.Add("ccc", "ccc", "ccc");
System.Data.DataTable dt2 = new System.Data.DataTable();
dt2.Columns.Add("Columns 5");
dt2.Rows.Add("aaa5");
bbb.Add(dt);
bbb.Add(dt2);
List<System.Data.DataTable> ListDataTable = new List<System.Data.DataTable>();
ListDataTable = bbb;
object objEndOfDoc = "\\endofdoc";
Microsoft.Office.Interop.Word.Document Wdc = new Microsoft.Office.Interop.Word.Document();
Microsoft.Office.Interop.Word.Range WordRange = Wdc.Bookmarks.get_Item(ref objEndOfDoc).Range;
Microsoft.Office.Interop.Word.Table wordTable;
for (int ListDataT = 0; ListDataT < ListDataTable.Count; ListDataT++)
{
int iRowCount = ListDataTable[ListDataT].Rows.Count;
int iColCount = ListDataTable[ListDataT].Columns.Count;
object objMissing = System.Reflection.Missing.Value;
wordTable = Wdc.Tables.Add(WordRange, iRowCount, iColCount, ref objMissing, ref objMissing);
int iTableRow = 1;
int iTableCol = 1;
for (int i = 0; i < ListDataTable[ListDataT].Columns.Count; i++)
{
wordTable.Cell(iTableRow, iTableCol).Range.Text = ListDataTable[ListDataT].Columns[i].ColumnName;
iTableCol++;
}
iTableRow++;
for (int i = 0; i < ListDataTable[ListDataT].Rows.Count; i++)
{
iTableCol = 1;
for (int j = 0; j < ListDataTable[ListDataT].Columns.Count; j++)
{
wordTable.Cell(iTableRow, iTableCol).Range.Text = ListDataTable[ListDataT].Rows[i][j].ToString();
// Console.Write(dt.Rows[i][j].ToString());
iTableCol++;
}
iTableRow++;
}
wordTable.Borders.Enable = 1;
wordTable.set_Style("Light Grid - Accent 3");
}
Wdc.SaveAs("c://test.docx");
Wdc.Close();
There are two possibilities:
1) Format the first row of the table with the paragraph formatting "Page Break Before".
2) Insert a manual Page Break between each table (keyboard equivalent: Shift+Enter).
Being a Word professional, my inclination is to use (1) unless something speaks against it. Most people, however, tend to use (2) because it's more obvious/discoverable.
wordTable.Rows[1].Range.ParagraphFormat.PageBreakBefore = true;
OR
Word.Range rng = wordTable.Range;
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
rng.InsertBreak(Word.WdBreakType.wdPageBreak);
I have an Array of Tables. For example 6 x 6. and a PlaceHolder.
I need to place the tables 6 next to each other in the PlaceHolder and then a new line of 6 next to each other, etc. What css properties do I add for each grid to achieve this.
I have
LiteralControl ltr = new LiteralControl();
ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" + #".fl { float: left}</style>";
this.Page.Header.Controls.Add(ltr);
Table[,] tableArray = new Table[6,6];
for (int j = 0; j < tableArray.GetLength(0); j++)
{
bool first = true;
for (int i = 0; i < tableArray.GetLength(1); i++)
{
if (first)
{
tableArray[j, i].CssClass = "mGrid";
first = false;
}
else
{
tableArray[j, i].CssClass = "fl mGrid";
}
tableArray[j, i].Width = Unit.Percentage(100 / 6);
PlaceHolderTables.Controls.Add(tableArray[j, i]);
}
}
But I do not know how to start a new row and then have 5 next to it etc. I am inexperienced with CSS. The tables has been initialised else where. mGrid is defined elsewhere as well.
You can place those 36 tables inside a table with 6x6.
protected void Page_Load(object sender, EventArgs e)
{
LiteralControl ltr = new LiteralControl();
ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" + #".fl { float: left}</style>";
Page.Header.Controls.Add(ltr);
Table main = new Table();
for (int i = 0; i < 6; i++)
{
TableRow row = new TableRow();
for (int j = 0; j < 6; j++)
{
Table table = CreateTable($"{i}x{j}");
TableCell cell = new TableCell();
cell.Controls.Add(table);
row.Controls.Add(cell);
}
main.Controls.Add(row);
}
PlaceHolderTables.Controls.Add(main);
}
private Table CreateTable(string text)
{
TableCell cell = new TableCell();
cell.Controls.Add(new Literal {Text = text });
TableRow row = new TableRow();
row.Cells.Add(cell);
Table table = new Table();
table.Rows.Add(row);
return table;
}
I'm using following method to create and position the excel chart beside table data. below code is working fine, but chart position(height) is creating problem when number of charts increase.
There is any solution for draw chart with cell value? or other thing that may be used by me to keep chart beside table data.
I want to print result of following method page by page and therefore want to place it correctly.
below is my code:
Excel.Application xla = new Excel.Application();
int height=75;
string uppercell = "B12";
int cell = 12;
if (CheckBox1.Checked == true)
{
string table_name, chart_name;
table_name = "Ration Table";
chart_name = "Ratio";
string st = "";
con.Open();
trying(ws, st, height, uppercell, cell, table_name, chart_name);
con.Close();
cell = cell + 33;
uppercell = "B" + cell;
height = 496 + 75;//height + 300;
}
public void trying(Excel.Worksheet ws,string st,double height,string uppercell,int cell,string table_name,string chart_name)
{
MySqlDataAdapter da = new MySqlDataAdapter(st, con);
System.Data.DataTable dtMainSQLData = new System.Data.DataTable();
da.Fill(dtMainSQLData);
DataColumnCollection dcCollection = dtMainSQLData.Columns;
//int cell = System.Int32.Parse(uppercell.Substring(1));
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
//Excel.ChartObject chartObj = chartObjs.Add(left, top, width, height);
Excel.ChartObject chartObj = chartObjs.Add(260, height, 350, 210);
Excel.Chart xlChart = chartObj.Chart;
//ws.Shapes.Item("xlChart").Top = (float)(double)ws.get_Range("E6").Top;//this.Controls.AddChart(this.Range["D2", "H12"]"chart1");
int nRows = dtMainSQLData.Rows.Count;
int nColumns = dtMainSQLData.Columns.Count;
string upperLeftCell = uppercell;// "B10";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1)) + nRows - 1;
char endColumnLetter = System.Convert.ToChar(Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}", endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}", endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = cell - 1; i < dtMainSQLData.Rows.Count + cell; i++)
{
for (int j = 2; j < dtMainSQLData.Columns.Count + 2; j++)
{
if (i == cell - 1)
{
xla.Cells[i, j] = dcCollection[j - 2].ToString();
}
else
{
xla.Cells[i, j] = dtMainSQLData.Rows[i - cell][j - 2].ToString();
}
}
}
//ws.Columns.AutoFit();
//for (int i = 1; i <= dtMainSQLData.Rows.Count; i++)
//{
// rg[1, i] = dtMainSQLData.Rows[i - 1][0].ToString(); //For Adding Header Text
// rg[2, i] = int.Parse(dtMainSQLData.Rows[i - 1][1].ToString()); //For Adding Datarow Value
//}
int lcellh = cell - 10;
int rcellh = cell - 10;
string lcellh1 = "B" + lcellh;
string rcellh1 = "L" + rcellh;
//-----------------------for company name and address-------------------------//
Excel.Range chartRange3;
ws.get_Range(lcellh1, rcellh1).Merge(false);//----------------------------------upperleft_cell, lowerright_cell
chartRange3 = ws.get_Range(lcellh1, rcellh1);
chartRange3.FormulaR1C1 = "BLUE BIRD FOODS (I) PVT.LTD.";//----------------------------------company name
chartRange3.HorizontalAlignment = 3;
chartRange3.VerticalAlignment = 3;
chartRange3.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
chartRange3.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.PaleVioletRed);
chartRange3.Font.Size = 20;
Excel.Range formatRange3;
formatRange3 = ws.get_Range(lcellh1, rcellh1);//----------------------------------hrow_border1, hrow_border2
formatRange3.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
//------for making header font bold
int hcell = cell - 1;
string hleftrange = "B" + hcell;
string hrightrange = "D" + hcell;
Excel.Range formatRange1;
formatRange1 = ws.get_Range(hleftrange);//----------------------------------hrow_bold
formatRange1.EntireRow.Font.Bold = true;
formatRange1.HorizontalAlignment = 3;
formatRange1.VerticalAlignment = 3;
//ws.Cells[1, 3] = "Bold";
//-------for giving broder to header
Excel.Range formatRange2;
formatRange2 = ws.get_Range(hleftrange, hrightrange);//----------------------------------hrow_border1, hrow_border2
formatRange2.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
//-------for giving broder to table data
Excel.Range formatRange;
formatRange = ws.get_Range(upperLeftCell, lowerRightCell);//----------------------------------upperLeftCell, lowerRightCell
formatRange.BorderAround(Excel.XlLineStyle.xlContinuous,
Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic,
Excel.XlColorIndex.xlColorIndexAutomatic);
formatRange.HorizontalAlignment = 3;
formatRange.VerticalAlignment = 3;
//--------for giving name to the table
int lcell = cell - 3;
int rcell = cell - 2;
string tleftrange = "B" + lcell;
string trightrange = "D" + rcell;
Excel.Range chartRange1;
ws.get_Range(tleftrange, trightrange).Merge(false);//----------------------------------upperleft_cell, lowerright_cell
formatRange2 = ws.get_Range(tleftrange, trightrange);
formatRange2.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
chartRange1 = ws.get_Range(tleftrange, trightrange);
chartRange1.FormulaR1C1 = table_name;//"Ratio table";//----------------------------------table_name
chartRange1.HorizontalAlignment = 3;
chartRange1.VerticalAlignment = 3;
chartRange1.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
chartRange1.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.PaleVioletRed);
chartRange1.Font.Size = 20;
//--------drawing chart with range
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, System.Reflection.Missing.Value);
xlChart.ChartType = Excel.XlChartType.xl3DPie;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
Excel.XlAxisGroup.xlPrimary);
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = chart_name;// "Ratio";
// *****************Set legend:***************************
xlChart.HasLegend = true;
}