Esempio n. 1
0
        private void addTable(Section section)
        {
            String[]   header = { "Name", "Capital", "Continent", "Area", "Population" };
            String[][] data   =
            {
                new String[] { "Argentina",                "Buenos Aires", "South America", "2777815", "32300003"  },
                new String[] { "Bolivia",                  "La Paz",       "South America", "1098575", "7300000"   },
                new String[] { "Brazil",                   "Brasilia",     "South America", "8511196", "150400000" },
                new String[] { "Canada",                   "Ottawa",       "North America", "9976147", "26500000"  },
                new String[] { "Chile",                    "Santiago",     "South America", "756943",  "13200000"  },
                new String[] { "Colombia",                 "Bagota",       "South America", "1138907", "33000000"  },
                new String[] { "Cuba",                     "Havana",       "North America", "114524",  "10600000"  },
                new String[] { "Ecuador",                  "Quito",        "South America", "455502",  "10600000"  },
                new String[] { "El Salvador",              "San Salvador", "North America", "20865",   "5300000"   },
                new String[] { "Guyana",                   "Georgetown",   "South America", "214969",  "800000"    },
                new String[] { "Jamaica",                  "Kingston",     "North America", "11424",   "2500000"   },
                new String[] { "Mexico",                   "Mexico City",  "North America", "1967180", "88600000"  },
                new String[] { "Nicaragua",                "Managua",      "North America", "139000",  "3900000"   },
                new String[] { "Paraguay",                 "Asuncion",     "South America", "406576",  "4660000"   },
                new String[] { "Peru",                     "Lima",         "South America", "1285215", "21600000"  },
                new String[] { "United States of America", "Washington",   "North America", "9363130", "249200000" },
                new String[] { "Uruguay",                  "Montevideo",   "South America", "176140",  "3002000"   },
                new String[] { "Venezuela",                "Caracas",      "South America", "912047",  "19700000"  }
            };
            Spire.Doc.Table table = section.AddTable();
            table.ResetCells(data.Length + 1, header.Length);

            // ***************** First Row *************************
            TableRow row = table.Rows[0];

            row.IsHeader            = true;
            row.Height              = 20; //unit: point, 1point = 0.3528 mm
            row.HeightType          = TableRowHeightType.Exactly;
            row.RowFormat.BackColor = Color.Gray;
            for (int i = 0; i < header.Length; i++)
            {
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                Paragraph p = row.Cells[i].AddParagraph();
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                TextRange txtRange = p.AppendText(header[i]);
                txtRange.CharacterFormat.Bold = true;
            }

            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height              = 20;
                dataRow.HeightType          = TableRowHeightType.Exactly;
                dataRow.RowFormat.BackColor = Color.Empty;
                for (int c = 0; c < data[r].Length; c++)
                {
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);
                }
            }
        }
Esempio n. 2
0
        private static void addTable(Section section, List <string[]> outData, int columns)
        {
            Spire.Doc.Table table = section.AddTable();
            table.ResetCells(outData.Count, columns);

            // ***************** First Row *************************
            TableRow row = table.Rows[0];

            row.IsHeader            = true;
            row.Height              = 30; //unit: point, 1point = 0.3528 mm
            row.HeightType          = TableRowHeightType.AtLeast;
            row.RowFormat.BackColor = Color.Gray;
            for (int i = 0; i < columns; i++)
            {
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                Paragraph p = row.Cells[i].AddParagraph();
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                TextRange txtRange = p.AppendText(outData[0][i]);
                txtRange.CharacterFormat.Bold = true;
            }

            for (int r = 1; r < outData.Count; r++)
            {
                TableRow dataRow = table.Rows[r];
                dataRow.Height              = 20;
                dataRow.HeightType          = TableRowHeightType.AtLeast;
                dataRow.RowFormat.BackColor = Color.Empty;
                for (int c = 0; c < columns; c++)
                {
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    if (outData[r].Length <= c)
                    {
                        dataRow.Cells[c].AddParagraph().AppendText("");
                    }
                    else
                    {
                        if (outData[r][c].Contains("##"))
                        {
                            dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            dataRow.Height              = 30;
                            dataRow.HeightType          = TableRowHeightType.AtLeast;
                            dataRow.RowFormat.BackColor = Color.Gray;

                            TextRange textRange = dataRow.Cells[c].AddParagraph().AppendText(outData[r][c].TrimStart('#'));
                            textRange.CharacterFormat.Bold = true;
                        }
                        else
                        {
                            dataRow.Cells[c].AddParagraph().AppendText(outData[r][c]);
                        }
                    }
                }
            }
        }
Esempio n. 3
0
        private void ExprtWord(object sender, RoutedEventArgs e)
        {
            //initial data source
            listStu      = exportStu.getStuData();
            dataRowCount = listStu.Count + 1;
            string path;

            //creat document、settion and table
            Spire.Doc.Section stuInfoSection = wordDocument.AddSection();
            Spire.Doc.Table   stuTable       = stuInfoSection.AddTable(true);
            stuTable.ResetCells(dataRowCount, columeCount);

            //set header
            Spire.Doc.TableRow row = stuTable.Rows[0];//initial TableRow
            row.IsHeader = true;
            for (int i = 0; i < columeCount; i++)
            {
                para = row.Cells[i].AddParagraph();
                TR   = para.AppendText(strHeader[i]);
            }

            //fill data
            for (int i = 1; i < dataRowCount; i++)
            {
                for (int j = 0; j < columeCount; j++)
                {
                    para = stuTable.Rows[i].Cells[j].AddParagraph();
                    TR   = para.AppendText(listStu[i - 1].GetValue(listStu[i - 1].propertyIndex[j]));
                }
            }

            //

            //save file
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Word Documents(*.docx)|*.docx";
            var res = saveFileDialog.ShowDialog();

            if (res != true)
            {
                return;
            }
            path = saveFileDialog.FileName;
            MessageBox.Show(path);

            wordDocument.SaveToFile(@path, FileFormat.Docx);
            wordDocument.Close();
        }
Esempio n. 4
0
        private void saveMyWordFile(string filename)
        {
            DataTable dt = new DataTable();

            listViewToDataTable(ResultList, dt);


            Document document = new Document();
            Section  section  = document.AddSection();

            Spire.Doc.Table table = section.AddTable(true);

            if (dt != null)
            {
                table.ResetCells(dt.Rows.Count + 1, dt.Columns.Count);
                TableRow row = table.Rows[0];
                row.IsHeader            = true;
                row.HeightType          = TableRowHeightType.Exactly;
                row.RowFormat.BackColor = Color.Gray;

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    Paragraph para = row.Cells[i].AddParagraph();
                    TextRange TR   = para.AppendText(dt.Columns[i].Caption.ToString());
                    TR.CharacterFormat.FontName = "宋体";
                    TR.CharacterFormat.FontSize = 14;
                    TR.CharacterFormat.Bold     = true;
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TableRow row1 = table.Rows[i + 1];
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Paragraph para = row1.Cells[j].AddParagraph();
                        TextRange TR   = para.AppendText(dt.Rows[i][j].ToString());
                        TR.CharacterFormat.FontName = "宋体";
                        TR.CharacterFormat.FontSize = 12;
                    }
                }

                document.SaveToFile(filename);

                System.Diagnostics.Process.Start(filename);
            }
        }
Esempio n. 5
0
        private void addTable(Section section, int id)
        {
            String[] header = new String[CComLibrary.GlobeVal.filesave.mtablecol1.Count + 1];

            header[0] = "序号";
            for (int i = 0; i < CComLibrary.GlobeVal.filesave.mtablecol1.Count; i++)
            {
                header[i + 1] = CComLibrary.GlobeVal.filesave.mtablecol1[i].formulaname + "(" +
                                CComLibrary.GlobeVal.filesave.mtablecol1[i].myitemsignal.cUnits[
                    CComLibrary.GlobeVal.filesave.mtablecol1[i].myitemsignal.cUnitsel] + ")";
            }



            int wt = 0;

            for (int i = 1; i <= CComLibrary.GlobeVal.filesave.mtable1statistics.Count; i++)
            {
                if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].selected == true)
                {
                    wt = wt + 1;
                }
            }

            String[][] data = new String[CComLibrary.GlobeVal.filesave.currentspenumber + 1 + wt][];

            for (int i = 1; i <= CComLibrary.GlobeVal.filesave.currentspenumber + 1 + wt; i++)
            {
                data[i - 1] = new String[CComLibrary.GlobeVal.filesave.mtablecol1.Count + 1];
            }

            for (int i = 1; i <= CComLibrary.GlobeVal.filesave.currentspenumber + 1; i++)
            {
                data[i - 1][0] = i.ToString();
                for (int j = 0; j < CComLibrary.GlobeVal.filesave.mtablecol1.Count; j++)
                {
                    float t = 0;

                    string s = "";


                    //历史出错

                    if (CComLibrary.GlobeVal.filesave.dt.Rows[i - 1][CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname] is DBNull)
                    {
                        CComLibrary.GlobeVal.filesave.dt.Rows[i - 1][CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname] = 0;
                    }


                    if (CComLibrary.GlobeVal.filesave.dt.Columns[CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname].DataType == Type.GetType("System.String"))
                    {
                        s = Convert.ToString(CComLibrary.GlobeVal.filesave.dt.Rows[i - 1][CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname]);
                    }
                    else
                    {
                        t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Rows[i - 1][CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname]);


                        s = t.ToString("F" + CComLibrary.GlobeVal.filesave.mtablecol1[j].myitemsignal.precise.ToString().Trim());
                    }


                    data[i - 1][j + 1] = s;
                }
            }

            int mt = CComLibrary.GlobeVal.filesave.currentspenumber + 1;

            for (int i = 1; i <= CComLibrary.GlobeVal.filesave.mtable1statistics.Count; i++)
            {
                if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].selected == true)
                {
                    data[mt][0] = CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname;



                    for (int j = 0; j < CComLibrary.GlobeVal.filesave.mtablecol1.Count; j++)
                    {
                        float t = 0;

                        string s = "";



                        if (CComLibrary.GlobeVal.filesave.dt.Columns[CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname].DataType == Type.GetType("System.String"))
                        {
                            s = "---";
                        }
                        else
                        {
                            if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname == "最小值")
                            {
                                // t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("min(" + CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname + ")", ""));
                                int a = 0;
                                for (int k = 0; k < CComLibrary.GlobeVal.filesave.dt.Columns.Count; k++)
                                {
                                    if (CComLibrary.GlobeVal.filesave.dt.Columns[k].ColumnName == CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname)
                                    {
                                        a = k;
                                        break;
                                    }
                                }



                                string mo = CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName;
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = "@temp";
                                t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("min(" + "@temp" + ")", ""));
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = mo;
                            }
                            if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname == "最大值")
                            {
                                // t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("max(" + CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname + ")", ""));
                                int a = 0;
                                for (int k = 0; k < CComLibrary.GlobeVal.filesave.dt.Columns.Count; k++)
                                {
                                    if (CComLibrary.GlobeVal.filesave.dt.Columns[k].ColumnName == CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname)
                                    {
                                        a = k;
                                        break;
                                    }
                                }



                                string mo = CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName;
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = "@temp";
                                t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("max(" + "@temp" + ")", ""));
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = mo;
                            }
                            if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname == "平均值")
                            {
                                // t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("avg(" + CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname + ")", ""));

                                int a = 0;
                                for (int k = 0; k < CComLibrary.GlobeVal.filesave.dt.Columns.Count; k++)
                                {
                                    if (CComLibrary.GlobeVal.filesave.dt.Columns[k].ColumnName == CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname)
                                    {
                                        a = k;
                                        break;
                                    }
                                }



                                string mo = CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName;
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = "@temp";
                                t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("avg(" + "@temp" + ")", ""));
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = mo;
                            }
                            if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname == "标准偏差")
                            {
                                //  t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("StDev(" + CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname + ")", ""));
                                int a = 0;
                                for (int k = 0; k < CComLibrary.GlobeVal.filesave.dt.Columns.Count; k++)
                                {
                                    if (CComLibrary.GlobeVal.filesave.dt.Columns[k].ColumnName == CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname)
                                    {
                                        a = k;
                                        break;
                                    }
                                }



                                string mo = CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName;
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = "@temp";
                                t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("StDev(" + "@temp" + ")", ""));
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = mo;
                            }
                            if (CComLibrary.GlobeVal.filesave.mtable1statistics[i - 1].formulaname == "方差")
                            {
                                //  t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("Var(" + CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname + ")", ""));
                                int a = 0;
                                for (int k = 0; k < CComLibrary.GlobeVal.filesave.dt.Columns.Count; k++)
                                {
                                    if (CComLibrary.GlobeVal.filesave.dt.Columns[k].ColumnName == CComLibrary.GlobeVal.filesave.mtablecol1[j].formulaname)
                                    {
                                        a = k;
                                        break;
                                    }
                                }



                                string mo = CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName;
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = "@temp";
                                t = Convert.ToSingle(CComLibrary.GlobeVal.filesave.dt.Compute("Var(" + "@temp" + ")", ""));
                                CComLibrary.GlobeVal.filesave.dt.Columns[a].ColumnName = mo;
                            }


                            s = t.ToString("F" + CComLibrary.GlobeVal.filesave.mtablecol1[j].myitemsignal.precise.ToString().Trim());
                        }



                        if (CComLibrary.GlobeVal.filesave.mtablecol1[j].myitemsignal.cUnitKind == 19)
                        {
                            s = "";
                        }

                        data[mt][1 + j] = s;
                    }
                    mt = mt + 1;
                }
            }

            Spire.Doc.Table table = section.AddTable();
            table.ResetCells(data.Length + 1, header.Length);

            // ***************** First Row *************************
            TableRow row = table.Rows[0];

            row.IsHeader            = true;
            row.Height              = 20; //unit: point, 1point = 0.3528 mm
            row.HeightType          = TableRowHeightType.AtLeast;
            row.RowFormat.BackColor = Color.Gray;


            for (int i = 0; i < header.Length; i++)
            {
                row.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                Paragraph p = row.Cells[i].AddParagraph();
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                TextRange txtRange = p.AppendText(header[i]);
                txtRange.CharacterFormat.Bold             = true;
                row.Cells[i].CellFormat.Borders.LineWidth = 1;
            }

            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height              = 20;
                dataRow.HeightType          = TableRowHeightType.Exactly;
                dataRow.RowFormat.BackColor = Color.Empty;
                for (int c = 0; c < data[r].Length; c++)
                {
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    dataRow.Cells[c].AddParagraph().AppendText(data[r][c]);
                    dataRow.Cells[c].CellFormat.Borders.LineWidth = 1;
                }
            }
        }
Esempio n. 6
0
        public void Export(DataGridView dataGrid, string filename)
        {
            Spire.Doc.Document document = new Spire.Doc.Document();
            Spire.Doc.Section  section  = document.AddSection();
            section.PageSetup.Orientation = Spire.Doc.Documents.PageOrientation.Landscape;

            AddHeaderTitle(section);

            Spire.Doc.Table table       = section.AddTable(true);
            String[]        header      = { "ID", "Full Name", "Date of birth", "Gender", "Phone", "Email", "Position" };
            int             RowCount    = dataGrid.Rows.Count;
            int             ColumnCount = dataGrid.Columns.Count;

            String[][] data = new String[RowCount][];
            for (int i = 0; i < RowCount; i++)
            {
                data[i] = new String[ColumnCount];
            }

            //add rows
            for (int c = 0; c < ColumnCount; c++)
            {
                for (int r = 0; r < RowCount; r++)
                {
                    if (dataGrid.Rows[r].Cells[c].Value.GetType() == typeof(DateTime))
                    {
                        data[r][c] = ((DateTime)dataGrid.Rows[r].Cells[c].Value).ToString("dd/MM/yyyy");
                    }
                    else
                    {
                        data[r][c] = dataGrid.Rows[r].Cells[c].Value.ToString();
                    }
                }
            }

            table.ResetCells(data.Length + 1, header.Length);

            TableRow FRow = table.Rows[0];

            FRow.IsHeader = false;
            FRow.Height   = 23;
            //FRow.RowFormat.BackColor = Color.AliceBlue;
            for (int i = 0; i < header.Length; i++)
            {
                //Cell Alignment
                Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                p.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                //Data Format
                Spire.Doc.Fields.TextRange TR = p.AppendText(header[i]);
                TR.CharacterFormat.FontName  = "Calibri";
                TR.CharacterFormat.FontSize  = 14;
                TR.CharacterFormat.TextColor = Color.Black;
                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
                    Spire.Doc.Documents.Paragraph p2  = DataRow.Cells[c].AddParagraph();
                    Spire.Doc.Fields.TextRange    TR2 = p2.AppendText(data[r][c]);
                    //Format Cells
                    p2.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Center;
                    TR2.CharacterFormat.FontName  = "Calibri";
                    TR2.CharacterFormat.FontSize  = 12;
                    TR2.CharacterFormat.TextColor = Color.Black;
                }
            }

            //Save and Launch
            document.SaveToFile(filename);
            MessageBox.Show("Document Created Successfully!", "Export File", MessageBoxButtons.OK, MessageBoxIcon.Information);
            document.Close();
        }
        static void Main(string[] args)
        {
            Document  doc  = new Document();
            Section   sec  = doc.AddSection();
            Paragraph para = sec.AddParagraph();

            para.AppendText("Spire.Doc--- Create Table");
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;

            Spire.Doc.Table table = sec.AddTable(false);
            table.ResetCells(7, 3);
            //First Row
            TextRange range;
            TableRow  Row = table.Rows[0];

            Row.Height = 30;

            Row.Cells[0].CellFormat.BackColor = Color.LightBlue;
            para = Row.Cells[0].AddParagraph();
            para.AppendPicture(Image.FromFile(@"../../images/1.png"));
            range = para.AppendText(".Net");
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
            range.CharacterFormat.TextColor = Color.White;

            Row.Cells[1].CellFormat.BackColor = Color.LightGreen;
            para = Row.Cells[1].AddParagraph();
            para.AppendPicture(Image.FromFile(@"../../images/2.png"));
            range = para.AppendText(".WPF");
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
            range.CharacterFormat.TextColor = Color.White;

            Row.Cells[2].CellFormat.BackColor = Color.LightPink;
            para = Row.Cells[2].AddParagraph();
            para.AppendPicture(Image.FromFile(@"../../images/3.png"));
            range = para.AppendText("Silverlight");
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
            range.CharacterFormat.TextColor = Color.White;

            //From Second Row To Seventh Row
            for (int i = 1; i < table.Rows.Count; i++)
            {
                table.Rows[i].Height = 20;
                for (int j = 0; j < table.Rows[i].Cells.Count; j++)
                {
                    para = table.Rows[i].Cells[j].AddParagraph();
                    if (i < 5)
                    {
                        if (j == 0)
                        {
                            para.AppendPicture(Image.FromFile(@"../../images/red.png"));
                        }
                        else
                        {
                            para.AppendPicture(Image.FromFile(@"../../images/c.png"));
                        }
                    }

                    switch (i)
                    {
                    case 1:
                        para.AppendText("Spire.Doc");
                        break;

                    case 2:
                        para.AppendText("Spire.Office");
                        break;

                    case 3:
                        para.AppendText("Spire.XLS");
                        break;

                    case 4:
                        para.AppendText("Spire.PDF");
                        break;

                    case 5:
                        if (j < 2)
                        {
                            para.AppendPicture(Image.FromFile(@"../../images/c.png"));
                            para.AppendText("Spire.PDFViewer");
                        }
                        else
                        {
                            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                            para.AppendText("/");
                        }
                        break;

                    case 6:
                        if (j < 2)
                        {
                            if (j == 0)
                            {
                                para.AppendPicture(Image.FromFile(@"../../images/blue.png"));
                            }
                            else
                            {
                                para.AppendPicture(Image.FromFile(@"../../images/c.png"));
                            }
                            para.AppendText("Spire.Barcode");
                        }
                        else
                        {
                            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                            para.AppendText("/");
                        }
                        break;
                    }
                }
            }
            //Save and launch
            doc.SaveToFile(@"..\..\CreateTable.docx", FileFormat.Docx);
            doc.Close();
            System.Diagnostics.Process.Start(@"..\..\CreateTable.docx");
        }
Esempio n. 8
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「編輯書籤內容」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_Bookmark(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample_Bookmark.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);

                Spire.Doc.Bookmark bookmark = document.Bookmarks.FindByName("NAME");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("NAME");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Name) ? "" : model.Name, false);
                }
                bookmark = document.Bookmarks.FindByName("GENDER");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("GENDER");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false);
                }
                bookmark = document.Bookmarks.FindByName("EMAIL");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("EMAIL");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Email) ? "" : model.Email, false);
                }
                bookmark = document.Bookmarks.FindByName("ADDRESS");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("ADDRESS");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Address) ? "" : model.Address, false);
                }
                bookmark = document.Bookmarks.FindByName("PHONE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("PHONE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false);
                }
                bookmark = document.Bookmarks.FindByName("MOBILE");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("MOBILE");
                    bookmarkNavigator.ReplaceBookmarkContent(string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false);
                }



                Spire.Doc.Section tempSection = document.AddSection();
                string            html;
                ParagraphBase     replacementFirstItem;
                ParagraphBase     replacementLastItem;
                TextBodySelection selection;
                TextBodyPart      part;

                //HTML Contents: Desciprion1
                bookmark = document.Bookmarks.FindByName("DESCRIPTION1");
                if (bookmark != null)
                {
                    html = string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    //將內容各段落套用指定的樣式
                    for (int i = 0; i < tempSection.Paragraphs.Count; i++)
                    {
                        tempSection.Paragraphs[i].ApplyStyle("Basic");
                    }
                    part = new TextBodyPart(selection);

                    // locate the bookmark
                    bookmarkNavigator.MoveToBookmark("DESCRIPTION1");
                    //replace the content of bookmark
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    //remove temp section
                    document.Sections.Remove(tempSection);
                }

                //HTML Contents: Desciprion2
                bookmark = document.Bookmarks.FindByName("DESCRIPTION2");
                if (bookmark != null)
                {
                    tempSection = document.AddSection();
                    html        = string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2);
                    tempSection.AddParagraph().AppendHTML(html);
                    replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
                    replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
                    selection            = new TextBodySelection(replacementFirstItem, replacementLastItem);
                    part = new TextBodyPart(selection);

                    bookmarkNavigator.MoveToBookmark("DESCRIPTION2");
                    bookmarkNavigator.ReplaceBookmarkContent(part);
                    document.Sections.Remove(tempSection);
                }

                //圖片
                bookmark = document.Bookmarks.FindByName("IMG");
                if (bookmark != null)
                {
                    bookmarkNavigator.MoveToBookmark("IMG");
                    Spire.Doc.Section             section_img   = document.AddSection();
                    Spire.Doc.Documents.Paragraph paragraph_img = section_img.AddParagraph();
                    Image      img     = Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg"));
                    DocPicture picture = paragraph_img.AppendPicture(img);

                    bookmarkNavigator.InsertParagraph(paragraph_img);
                    document.Sections.Remove(section_img);
                }
                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    bookmarkNavigator.MoveToBookmark("TABLE");
                    bookmarkNavigator.InsertTable(table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section sections = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < sections.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = sections.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 透過既有的套印檔匯出 Word 文件 (以「取代文字」方式套印)
        /// </summary>
        /// <param name="result">回傳: 執行結果</param>
        /// <param name="msg">回傳: 訊息</param>
        /// <returns>串流資訊</returns>
        public byte[] ExportResumeByDocx_ReplaceText(out bool result, out string msg)
        {
            result = true;
            msg    = "";
            MemoryStream ms = new MemoryStream();

            try
            {
                Spire.Doc.Document document = new Spire.Doc.Document();

                //載入套印檔
                //注意: 實際運作時,若同一時間有兩位以上使用者同時進行套印,會產生「無法開啟已開啟檔案」的錯誤
                //建議實作時,一個使用者執行匯出動作時先複製一個套印檔,完成套印後再將複製的檔案刪除,即可避開錯誤
                document.LoadFromFile(HttpContext.Current.Server.MapPath("~/App_Data/MyResumeSample.docx"));

                #region 定義樣式

                //定義樣式 BasicStyle: 一般段落文字
                ParagraphStyle style = new ParagraphStyle(document)
                {
                    Name = "Basic"
                };
                //style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Justify;
                style.CharacterFormat.FontName = "標楷體";
                style.CharacterFormat.FontSize = 12;
                document.Styles.Add(style);

                #endregion

                //取得要套印的內容
                Resume model = new Resume();

                #region 套印內容

                document.Replace("{$Name$}", string.IsNullOrEmpty(model.Name) ? "" : model.Name, false, true);
                document.Replace("{$Gender$}", string.IsNullOrEmpty(model.Gender) ? "" : model.Gender, false, true);
                document.Replace("{$Email$}", string.IsNullOrEmpty(model.Email) ? "" : model.Email, false, true);
                document.Replace("{$Address$}", string.IsNullOrEmpty(model.Address) ? "" : model.Address, false, true);
                document.Replace("{$Phone$}", string.IsNullOrEmpty(model.Phone) ? "" : model.Phone, false, true);
                document.Replace("{$Mobile$}", string.IsNullOrEmpty(model.Mobile) ? "" : model.Mobile, false, true);

                //包含 HTML 字串需放置在 paragraph 內,
                //因此套印檔中的 {$Description1$} 及 {$Description2$} 需透過「以 paragraph 取代文字」方式替代
                //Replace {$Description1$} with paragraph
                TextSelection selection = document.FindString("{$Description1$}", false, true);
                TextRange     range     = selection.GetAsOneRange();
                Spire.Doc.Documents.Paragraph paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description1$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description1) ? "" : HttpUtility.HtmlDecode(model.Description1));

                //Replace {$Description2$} with paragraph
                selection = document.FindString("{$Description2$}", false, true);
                range     = selection.GetAsOneRange();
                paragraph = range.OwnerParagraph;
                paragraph.ApplyStyle("Basic");
                paragraph.Replace("{$Description2$}", "", false, false);
                paragraph.AppendHTML(string.IsNullOrEmpty(model.Description2) ? "" : HttpUtility.HtmlDecode(model.Description2));

                //Replace {$Img$} with Image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(Image.FromFile(HttpContext.Current.Server.MapPath("~/App_Data/Penguins.jpg")));

                selection = document.FindString("{$Img$}", false, true);
                range     = selection.GetAsOneRange();
                range.OwnerParagraph.ChildObjects.Insert(0, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);

                #endregion

                #region 動態新增表格

                if (model.JobHistory.Count > 0)
                {
                    Spire.Doc.Section s      = document.AddSection();
                    Spire.Doc.Table   table  = s.AddTable(true);
                    string[]          Header = { "序號", "任職公司", "職稱", "開始時間", "結束時間" };

                    //Add Cells
                    table.ResetCells(model.JobHistory.Count + 1, Header.Length);

                    //Header Row
                    TableRow FRow = table.Rows[0];
                    FRow.IsHeader = true;
                    for (int i = 0; i < Header.Length; i++)
                    {
                        Spire.Doc.Documents.Paragraph p = FRow.Cells[i].AddParagraph();
                        FRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                        p.Format.HorizontalAlignment = HorizontalAlignment.Center;

                        TextRange TR = p.AppendText(Header[i]);
                        TR.CharacterFormat.Bold = true;
                    }

                    //Data Row
                    model.JobHistory = model.JobHistory.OrderBy(x => x.StartDT).ToList();
                    for (int r = 0; r < model.JobHistory.Count; r++)
                    {
                        TableRow DataRow = table.Rows[r + 1];
                        string[] data    = new string[] { (r + 1).ToString(), model.JobHistory[r].CompanyName, model.JobHistory[r].JobTitle, (model.JobHistory[r].StartDT.HasValue ? model.JobHistory[r].StartDT.Value.ToShortDateString() : ""), (model.JobHistory[r].EndDT.HasValue ? model.JobHistory[r].EndDT.Value.ToShortDateString() : "") };

                        //Columns.
                        for (int c = 0; c < data.Length; c++)
                        {
                            //Cell Alignment
                            DataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;

                            //Fill Data in Rows
                            Spire.Doc.Documents.Paragraph p2 = DataRow.Cells[c].AddParagraph();
                            TextRange TR2 = p2.AppendText(data[c]);

                            //Format Cells
                            p2.Format.HorizontalAlignment = HorizontalAlignment.Center;
                        }
                    }

                    //Replace text with Table
                    TextSelection selectionTable = document.FindString("{$JobHistory$}", true, true);
                    TextRange     rangeTable     = selectionTable.GetAsOneRange();
                    Spire.Doc.Documents.Paragraph paragraphTable = rangeTable.OwnerParagraph;
                    Body body  = paragraphTable.OwnerTextBody;
                    int  index = body.ChildObjects.IndexOf(paragraphTable);
                    body.ChildObjects.Remove(paragraphTable);
                    body.ChildObjects.Insert(index, table);
                }

                #endregion

                #region 套用樣式

                //套用文章段落樣式
                for (int s = 0; s < document.Sections.Count; s++)
                {
                    Spire.Doc.Section section = document.Sections[s];
                    //套用文章段落樣式
                    for (int p = 0; p < section.Paragraphs.Count; p++)
                    {
                        Spire.Doc.Documents.Paragraph pgh = section.Paragraphs[p];
                        pgh.ApplyStyle("Basic");
                        pgh.Format.BeforeSpacing = 12;
                    }

                    //套用表格樣式
                    for (int t = 0; t < document.Sections[s].Tables.Count; t++)
                    {
                        Spire.Doc.Table table = (Spire.Doc.Table)document.Sections[s].Tables[t];
                        table.PreferredWidth            = new PreferredWidth(WidthType.Percentage, 100);
                        table.TableFormat.IsAutoResized = true;

                        //set table border
                        //table.TableFormat.Borders.Right.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Left.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Top.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Horizontal.BorderType = Spire.Doc.Documents.BorderStyle.Thick;
                        //table.TableFormat.Borders.Vertical.BorderType = Spire.Doc.Documents.BorderStyle.Thick;

                        for (int tr = 0; tr < table.Rows.Count; tr++)
                        {
                            for (int td = 0; td < table.Rows[tr].Cells.Count; td++)
                            {
                                for (int t_ph = 0; t_ph < table.Rows[tr].Cells[td].Paragraphs.Count; t_ph++)
                                {
                                    table.Rows[tr].Cells[td].Paragraphs[t_ph].ApplyStyle("Basic");
                                }
                            }
                        }
                    }
                }

                #endregion

                //匯出
                document.SaveToStream(ms, FileFormat.Docx);
            }
            catch (Exception ex)
            {
                result = false;
                msg    = ex.Message;
            }

            if (result)
            {
                return(ms.ToArray());
            }
            else
            {
                return(null);
            }
        }