生成Openxml发票已损坏

时间:2015-01-26 11:50:38

标签: c# sql .net openxml

我正在创建一个应用程序,用于扫描c#中数据表中的数据,并使用此数据填充文字处理文档上的相应内容控件以生成发票。为此,我使用以下代码

 private void GenerateInvoiceButton_Click(object sender, EventArgs e)
    {
        List<string> InvoicePerameters = new List<string> {ProjectOrderNumberTextBox.Text, FileDirectoryTextBox.Text, CustomerComboBox.SelectedItem.ToString(), ProjectComboBox.SelectedItem.ToString(), TemplateComboBox.SelectedItem.ToString(), DaysForRepaymentTrackBar.Value.ToString() };

        if (InvoicePerameters.Contains(""))
        {
            MessageBox.Show("All input perameters must be filled");
        }
        else
        {
            try
            {
                AccountVariables.Username = MenuUsername.Text;

                string PurchaceOrderNumber = ProjectOrderNumberTextBox.Text;
                string FileDirectory = FileDirectoryTextBox.Text;
                CustomerVariables.CustomerCompanyName = CustomerComboBox.SelectedItem.ToString();
                ProjectVariables.ProjectTableTitle = ProjectComboBox.SelectedItem.ToString();
                int SelectedCustomer = CustomerComboBox.SelectedIndex;
                int SelectedTemplate = TemplateComboBox.SelectedIndex;

                string TemplatePath = templateDatabaseDataSet.TemplateTable.Rows[SelectedTemplate][templateDatabaseDataSet.TemplateTable.TemplateDirectoryColumn].ToString();

                TemplatePath = TemplatePath.Substring(1, TemplatePath.Length - 2);

                string ContactName = "";

                string InvoiceDate = GeneralVariables.TodaysDate.ToString("dd/MM/yyyy");
                string DueDate = GeneralVariables.TodaysDate.AddDays(DaysForRepaymentTrackBar.Value).ToString("dd/MM/yyyy");

                string PaymentReference;


                for (int i = 0; i < customerDatabaseDataSet.CustomerTable.Rows.Count; ) //For each row in the customer data table
                {
                    bool CustomerCompanyNameExists = CustomerVariables.CustomerCompanyName == customerDatabaseDataSet.CustomerTable.Rows[i][customerDatabaseDataSet.CustomerTable.CustomerCompanyNameColumn].ToString();

                    bool CustomerOfUser = AccountVariables.Username == customerDatabaseDataSet.CustomerTable.Rows[i][customerDatabaseDataSet.CustomerTable.UserColumn].ToString();

                    if ((CustomerOfUser == true) && (CustomerCompanyNameExists == true))
                    {
                        ContactName = customerDatabaseDataSet.CustomerTable.Rows[i][customerDatabaseDataSet.CustomerTable.ContactNameColumn].ToString();

                        string InvoiceOutputPath = System.IO.Path.Combine(FileDirectory, String.Format("{0} - {1} - {2} - {3}.docx", GeneralVariables.NextInvoiceIDString, CustomerVariables.CustomerCompanyName, ContactName, DateTime.Now.ToString("yyyyMMdd")));

                        MessageBox.Show(TemplatePath + "\n\n" + InvoiceOutputPath);

                        File.Copy(TemplatePath, InvoiceOutputPath, true);

                        Dictionary<string, string> CustomerAddressDictionary = new Dictionary<string, string>
                        {
                            //Populate Customer Details
                            {"ContactName", ContactName},
                            {"CustomerName", CustomerVariables.CustomerCompanyName},
                            {"CustomerEmail", customerDatabaseDataSet.CustomerTable.Rows[i][10].ToString()},
                            {"CustomerAddressLine1", customerDatabaseDataSet.CustomerTable.Rows[i][2].ToString()},
                            {"CustomerAddressLine2", customerDatabaseDataSet.CustomerTable.Rows[i][3].ToString()},
                            {"CustomerAddressLine3", customerDatabaseDataSet.CustomerTable.Rows[i][4].ToString()},
                            {"CustomerCity", customerDatabaseDataSet.CustomerTable.Rows[i][5].ToString()},
                            {"CustomerCounty", customerDatabaseDataSet.CustomerTable.Rows[i][6].ToString()},
                            {"CustomerCountry", customerDatabaseDataSet.CustomerTable.Rows[i][7].ToString()},
                            {"CustomerPostcode", customerDatabaseDataSet.CustomerTable.Rows[i][8].ToString()},
                            {"CustomerTelephone", customerDatabaseDataSet.CustomerTable.Rows[i][11].ToString()}
                        };

                        int UserRowInt; //Declare variable UserRowInt
                        DataRow[] UserRows = accountDatabaseDataSet.AccountTable.Select("Username = '" + AccountVariables.Username + "'"); //Get array of all Usernames that match the username variable input

                        if (UserRows.Count() == 1) //If number of rows in user row is equal to 1
                        {
                            foreach (DataRow UserRow in UserRows) //For every item in the array UserRows
                            {
                                UserRowInt = accountDatabaseDataSet.AccountTable.Rows.IndexOf(UserRow); //Get value of row index and set the value of UserRowInt to this

                                Dictionary<string, string> UserAddressDictionary = new Dictionary<string, string>
                                {
                                    {"CompanyName", AccountVariables.Username},
                                    {"UserAddressLine1", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.AddressLine1Column].ToString()},
                                    {"UserAddressLine2", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.AddressLine2Column].ToString()},
                                    {"UserAddressLine3", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.AddressLine3Column].ToString()},
                                    {"City", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.CityColumn].ToString()},
                                    {"Postcode", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.PostcodeColumn].ToString()},
                                    {"Country", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.CountryColumn].ToString()},
                                    {"Telephone", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.TelephoneColumn].ToString()},
                                    {"Website", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.WebsiteColumn].ToString()},
                                    {"RegisteredCompanyNumber", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.RegisteredCompanyNumberColumn].ToString()},
                                    {"VATRegistrationNumber", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.VATRegistrationNumberColumn].ToString()},
                                };


                                PaymentReference = accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.PaymentReference_Column].ToString();

                                Dictionary<string, string> PaymentDetailsDictionary = new Dictionary<string, string>
                                {
                                    //Populate payment details
                                    {"InvoiceNumber", GeneralVariables.NextInvoiceIDString},
                                    {"InvoiceNumber2", GeneralVariables.NextInvoiceIDString},
                                    {"PurchaceOrderNumber", PurchaceOrderNumber},
                                    {"InvoiceDate", InvoiceDate},
                                    {"PaymentTerms", DaysForRepaymentTrackBar.Value.ToString()},
                                    {"DueDate", DueDate},
                                    {"Bank", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.BankColumn].ToString()},
                                    {"SortCode", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.SortcodeColumn].ToString()},
                                    {"AccountNumber", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.AccountNumberColumn].ToString()},
                                    {"IBAN", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.IBANColumn].ToString()},
                                    {"BIC", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.BICColumn].ToString()},
                                    {"PaymentReference", accountDatabaseDataSet.AccountTable.Rows[UserRowInt][accountDatabaseDataSet.AccountTable.PaymentReference_Column].ToString()},
                                };

                                WordprocessingDocument InvoiceDocument = WordprocessingDocument.Open(InvoiceOutputPath, true);
                                InvoiceDocument.ChangeDocumentType(WordprocessingDocumentType.Document);

                                MainDocumentPart MainInvoicePart = InvoiceDocument.MainDocumentPart;

                                foreach (string CustDetail in CustomerAddressDictionary.Keys)
                                {
                                    GeneralVariables.TextControl = GetContentControlByTag(MainInvoicePart, CustDetail);
                                    GeneralVariables.TextControl.Text = CustomerAddressDictionary[CustDetail];
                                }

                                foreach (string UserDetail in UserAddressDictionary.Keys)
                                {
                                    GeneralVariables.TextControl = GetContentControlByTag(MainInvoicePart, UserDetail);
                                    GeneralVariables.TextControl.Text = UserAddressDictionary[UserDetail];
                                }

                                foreach (string PayDetail in PaymentDetailsDictionary.Keys)
                                {
                                    GeneralVariables.TextControl = GetContentControlByTag(MainInvoicePart, PayDetail);
                                    GeneralVariables.TextControl.Text = PaymentDetailsDictionary[PayDetail];
                                }

                                Table DeliveredWorkItemTable = MainInvoicePart.Document.Body.Descendants<Table>().Last();
                                TableRow DeliveredWorkItemRow = DeliveredWorkItemTable.Elements<TableRow>().ElementAt(1);

                                bool WorkItemDelivered;
                                bool WorkItemApproved;

                                double RawTotal = 0;
                                double VAT = 0;

                                for (int Projectint = 0; Projectint < projectsDatabaseDataSet.ProjectsTable.Rows.Count; Projectint++)
                                {
                                    if (CustomerVariables.CustomerCompanyName == projectsDatabaseDataSet.ProjectsTable.Rows[Projectint][projectsDatabaseDataSet.ProjectsTable.CustomerColumn].ToString())
                                    {
                                        for (int index = 0; index < projectsDatabaseDataSet.WorkItemTable.Rows.Count; index++)
                                        {
                                            if (ProjectVariables.ProjectTableTitle == projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.ProjectColumn].ToString())
                                            {
                                                WorkItemDelivered = projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.DeliveredColumn].ToString() == "true";
                                                WorkItemApproved = projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.ApprovedColumn].ToString() == "true";

                                                if ((WorkItemDelivered == true) && (WorkItemApproved == true))
                                                {
                                                    RawTotal = RawTotal + (double)projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.TotalCostColumn];

                                                    TableRow ApprovedWorkItemRow = (TableRow)DeliveredWorkItemRow.CloneNode(true);
                                                    ApprovedWorkItemRow.Descendants<TableCell>().ElementAt(0).Append(new Paragraph(new Run(new Text(projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.DateColumn].ToString()))));
                                                    ApprovedWorkItemRow.Descendants<TableCell>().ElementAt(1).Append(new Paragraph(new Run(new Text(projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.DescriptionColumn].ToString()))));
                                                    ApprovedWorkItemRow.Descendants<TableCell>().ElementAt(2).Append(new Paragraph(new Run(new Text(((double)projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.TimeColumn]).ToString()))));
                                                    ApprovedWorkItemRow.Descendants<TableCell>().ElementAt(3).Append(new Paragraph(new Run(new Text("£" + ((double)projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.CostPerHourColumn]).ToString()))));
                                                    ApprovedWorkItemRow.Descendants<TableCell>().ElementAt(4).Append(new Paragraph(new Run(new Text("£" + ((double)projectsDatabaseDataSet.WorkItemTable.Rows[index][projectsDatabaseDataSet.WorkItemTable.TotalCostColumn]).ToString()))));

                                                    DeliveredWorkItemTable.InsertAt(ApprovedWorkItemRow, 4);
                                                }
                                            }
                                        }
                                    }
                                }

                                DeliveredWorkItemTable.RemoveChild(DeliveredWorkItemRow);

                                VAT = RawTotal * AccountVariables.VATRatePercentage;

                                double Total = RawTotal + VAT;

                                Dictionary<string, string> TotalValues = new Dictionary<string, string>
                                {
                                    //Populate total values
                                    {"Subtotal", RawTotal.ToString("C")},
                                    {"TotalVAT", VAT.ToString("C")},
                                    {"Total", Total.ToString("C")}
                                };

                                foreach (string Placeholder in TotalValues.Keys)
                                {
                                    GeneralVariables.TextControl = GetContentControlByTag(MainInvoicePart, Placeholder);
                                    GeneralVariables.TextControl.Text = TotalValues[Placeholder];
                                }

                                InvoiceDocument.MainDocumentPart.Document.Save();

                                AccountVariables.InvoiceRow = accountDatabaseDataSet.InvoiceTable.NewInvoiceTableRow();
                                AccountVariables.InvoiceRow.InvoiceID = GeneralVariables.NextInvoiceID;
                                AccountVariables.InvoiceRow.InvoiceDate = GeneralVariables.TodaysDate;
                                AccountVariables.InvoiceRow.DueDate = GeneralVariables.TodaysDate.AddDays(DaysForRepaymentTrackBar.Value);
                                accountDatabaseDataSet.InvoiceTable.AddInvoiceTableRow(AccountVariables.InvoiceRow);

                                invoiceTableTableAdapter.Update(accountDatabaseDataSet.InvoiceTable);
                                accountDatabaseDataSet.AcceptChanges();

                                AccountVariables.AccountDatabaseConnection.Close();

                                //Set NextInvoiceID
                                GeneralVariables.NextInvoiceID = GeneralVariables.NextInvoiceID + 1;

                                GeneralVariables.CurrentPanel.Visible = false; //Make current panel invisible
                                HomePage.Visible = true;

                                GeneralVariables.PreviousPanel = GeneralVariables.CurrentPanel; //Set Previous panel value as the page that has been left
                                GeneralVariables.CurrentPanel = HomePage; //Set current panel value to home page

                                HomeTitle.Text = "Home";
                                EditAccountButton.Text = "Edit account details";
                                VATRateLabel.Text = "VAT Rate    " + AccountVariables.VATRatePercentage + "%"; //Set VAT rate label to show value of the percentage VAT

                                int TotalProjects = 0; //Declare variable Total Projects
                                int TotalCustomers = 0; //Declare variable Total Customers

                                //Set VAT track bar to vat rate
                                VATRateTrackBar.Value = (int)AccountVariables.VATRate;

                                //Set customers variables
                                int TotalTemplates = templateDatabaseDataSet.TemplateTable.Rows.Count;

                                for (int index = 0; index < customerDatabaseDataSet.CustomerTable.Rows.Count; )
                                {
                                    if (AccountVariables.Username == customerDatabaseDataSet.CustomerTable.Rows[index][customerDatabaseDataSet.CustomerTable.UserColumn].ToString())
                                    {
                                        //set total customers
                                        TotalCustomers = TotalCustomers + 1; //Add 1 to the value of total customers

                                        CustomerVariables.CustomerCompanyName = customerDatabaseDataSet.CustomerTable.Rows[index][customerDatabaseDataSet.CustomerTable.CustomerCompanyNameColumn].ToString();

                                        for (int ProjectIndex = 0; ProjectIndex < projectsDatabaseDataSet.ProjectsTable.Rows.Count; )
                                        {
                                            if (CustomerVariables.CustomerCompanyName == projectsDatabaseDataSet.ProjectsTable.Rows[ProjectIndex][projectsDatabaseDataSet.ProjectsTable.CustomerColumn].ToString())
                                            {
                                                TotalProjects = TotalProjects + 1; //Add 1 to the value of total projects

                                                ProjectIndex++; //Move on to next project index
                                            }
                                            else
                                            {
                                                ProjectIndex++; //Move on to next project index
                                            }
                                        }

                                        i++; //Move on to next index value
                                    }
                                    else
                                    {
                                        i++; //Move on to next index value
                                    }
                                }

                                //Display totals
                                TotalCustomersLabel.Text = "Total customers";
                                TotalProjectsLabel.Text = "Total Projects";
                                TotalTemplatesLabel.Text = "Total templates";
                                InvoicesGeneratedLabel.Text = "Invoices generated";
                                TotalCustomersOutput.Text = TotalCustomers.ToString();
                                TotalProjectsOutput.Text = TotalProjects.ToString();
                                TotalTemplatesOutput.Text = TotalTemplates.ToString();
                                InvoicesGeneratedOutput.Text = (GeneralVariables.NextInvoiceID - 1).ToString();
                            }
                        }

                        i++; //Move on to next index value
                    }
                    else
                    {
                        i++; //Move on to next index value
                    }
                }  
            }
            catch (Exception ex) //Catch thrown error
            {
                MessageBox.Show(ex.Message + "\n\n" + ex.TargetSite + "\n\n" + ex.StackTrace); //Output error as message
            }
        }
    }

填写以下模板

![模板] [1]

当我使用以下数据创建发票时

![用户选择的生成发票数据] [2]

然后按生成发票按钮,屏幕进入主页,然后冻结。当我结束任务并查看此文件夹时,文档已正确保存。但是,当我打开此文档时,出现错误

&#34;我们很抱歉。我们无法打开0002-Another Company-John Smith - 20150126,因为我们发现其内容存在问题。 详细信息:Microsoft Office无法打开此文件,因为某些部分缺失或无效&#34;

0 个答案:

没有答案