EPPlus对象参考保存文件时出错。为什么会这样呢?

时间:2019-12-05 04:57:03

标签: c# epplus

我正在创建一个向Excel写入一些数据的基本程序。我是C#的新手,当然是EPPlus的新手。我一直很难找到有关此软件包的良好文档,但是。.

我的代码如下。

using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OfficeOpenXml;
using Microsoft.VisualBasic;

/* CHANGELOG
 * 11/26/2019
 * Added basic support for excel database using EPPlus library
 * 
 */



/* BUGS, FIXES, AND TODO
 * 
 * ******BUGS******
 * 
 * [] Fix loop to loop through each item in given array instead of specified length. Perhaps a foreach makes more sense?
 *
 *    
 *    
 * ******TODO******   
 * [x] Figure out best way to write information to a file (Excel?)
 * [] Create Duplicate Entry detector?
 * [] Possible to loop through args in visitor constructor?
 * [] Prefill information from membership info (Bar code on mem card?)   
 * [] Set tab index of all items   
 * [] Allow user to export database to excel w/ path of choosing.
 * [] 
 *    
 *    
 */


namespace Nonprofit_Attendance_App
{

    public partial class Form1 : Form
    {

        //Declare Global Variables
        public static class Globals
        {

            public static string excelSheet = "";
            public static ExcelWorksheet wsSheet1;
            public static ExcelPackage ExcelPkg;
            public static string userIn;
            public static string[] alphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
            public static int dataPosition;
        }


        public Form1()
        {

            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create new visitor object with form input
            Visitor Paal = new Visitor( vis_zip.Text, 
                vis_entrance_courtYard.Checked, 
                vis_entrance_frontDoor.Checked, 
                vis_reason_general.Checked, 
                vis_reason_meeting.Checked, 
                vis_reason_photography.Checked, 
                vis_reason_cafe.Checked, 
                vis_firstTime.Checked, 
                vis_returning.Checked, 
                vis_both.Checked, 
                vis_mem.Checked, 
                vis_mem_lastName.Text );

            //Loop through Visitor object to write data to console. DELETE EVENTUALLY

            foreach (var item in Paal.vis_data)
            {

            Console.WriteLine(item);

            }

            writeData(Paal.vis_data);



            //Clear form after submit 
            vis_zip.Text = string.Empty;
            vis_entrance_courtYard.Checked = false;
            vis_entrance_frontDoor.Checked = false;
            vis_reason_general.Checked = false;
            vis_reason_meeting.Checked = false;
            vis_reason_photography.Checked = false;
            vis_reason_cafe.Checked = false;
            vis_firstTime.Checked = false;
            vis_returning.Checked = false;
            vis_both.Checked = false;
            vis_mem.Checked = false;
            vis_mem_lastName.Text = string.Empty;

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        class Visitor
        { 
            public string[] vis_data = new string[12];
            public Visitor(string zipCode, bool entrance_courtYard, bool entrance_frontDoor, bool vis_reason_general, bool vis_reason_meeting, bool vis_reason_photo, bool vis_reason_cafe, bool vis_firstTime, bool vis_Returning, bool vis_both, bool vis_mem, string vis_mem_lastName)
            {
                //Write to Excel Sheet
                //FIX EMPTY ENTRIES
                vis_data[0] = zipCode;

                if (entrance_courtYard == true)
                {
                    vis_data[1] = "Courtyard";
                }
                else
                {
                    vis_data[1] = "Front Door";
                }

                if (vis_reason_general == true)
                {
                    vis_data[2] += "General Visit";
                }
                else if (vis_reason_meeting == true)
                {
                    vis_data[2] += "Meeting";
                }
                else if (vis_reason_cafe == true)
                {
                    vis_data[2] += "Cafe";
                }
                else if (vis_reason_photo == true)
                {
                    vis_data[2] += "Photography";
                }
                else
                {
                    vis_data[2] = "null";
                }

                if (vis_firstTime == true)
                {
                    vis_data[3] = "First Time";
                }
                else if (vis_Returning == true)
                {
                    vis_data[3] = "Returning";
                }
                else if (vis_both == true)
                {
                    vis_data[3] = "Both";
                }
                else
                {
                    vis_data[3] = "null";
                }


                if (vis_mem)
                {
                    vis_data[4] = vis_mem_lastName;
                }
                else
                {
                    vis_data[4] = "Not a member";
                }

                vis_data[5] = DateTime.Now.ToString();
            }
        }

        private void vis_frontDoor_CheckedChanged(object sender, EventArgs e)
        {

        }

        //Enable member last name when member checkbox is checked
        private void vis_mem_CheckedChanged(object sender, EventArgs e)
        {
            if (vis_mem.Checked)
            {
                vis_mem_lastName.Enabled = true;
            } 
            else
            {
                vis_mem_lastName.Enabled = false;
            }

        }

        private void vis_mem_lastName_TextChanged(object sender, EventArgs e)
        {

        }


        //Generates Excel database
        public static void generateExcel()
        {
            //get user input for database name

            //Excel Sheet Generation
            Globals.ExcelPkg = new ExcelPackage();
            Globals.wsSheet1 = Globals.ExcelPkg.Workbook.Worksheets.Add("Sheet1");
            Globals.wsSheet1.Protection.IsProtected = false;
            Globals.wsSheet1.Protection.AllowSelectLockedCells = false;
            Globals.excelSheet = @"C:\Users\paalw\documents\database.xlsx";
            Globals.ExcelPkg.SaveAs(new FileInfo(@"C:\Users\paalw\documents\database.xlsx"));

        }
        //TO FINISH
        public static void setHeaders()
        {

            using (ExcelRange Rng = Globals.wsSheet1.Cells)
            {
                for (int i = 0; i < 12; i++)
                {
                     Rng[Globals.alphabet[i] + 1].Value = i;
                }

            }

        }

        public void getDataPosition()
        {
            using (ExcelRange Rng = Globals.wsSheet1.Cells)
            {
                for (int i = 0; i < 5; i++)
                {
                    if (Convert.ToBoolean(Rng["A" + i].Value) == false)
                    {
                        Globals.dataPosition = i;
                        Console.WriteLine(Globals.dataPosition);
                        break;
                    }


                }
            }
        }

        public void writeData(string[] x)
        {

            using (ExcelRange Rng = Globals.wsSheet1.Cells)

            {
                int i = 0;
                int j = Globals.dataPosition;
                foreach (var item in x)
                {
                    Rng[Globals.alphabet[i] + j].Value = x[i];
                    i++;
                }
                Globals.dataPosition++;
            }

        }


        private void fileToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        { 

            if (File.Exists(Globals.excelSheet))
            {
                Globals.excelSheet = @"C:\Users\paalw\documents\database.xlsx";

                //NEED TO set FileLocation to existing Sheet
                MessageBox.Show("Connected to Databse");
                getDataPosition();
            }
            else
            {

                generateExcel();
                setHeaders();
                getDataPosition();

            }
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

            Globals.ExcelPkg.Save();
        }
    }
}

当我运行Globals.ExcelPkg.Save();时,无论它在程序中的什么位置或何时运行,我都会不断收到对象引用错误:

对象引用未设置为对象的实例。

我不清楚为什么会这样,因为当我运行generateExcel()时;方法,应将Globals.ExcelPkg设置为正在创建的当前数据库。就像每当应用程序运行时,它将完全清除该变量一样。任何帮助将不胜感激,因为在上周我一直在为此努力。

1 个答案:

答案 0 :(得分:0)

以上代码在System.NullReferenceException的{​​{1}}处将Object reference not set to an instance of an objectusing (ExcelRange Rng = Globals.wsSheet1.Cells)抛出

因为writeData(string[] x)是在wsSheet1类中声明的,但尚未初始化。另外,在保存Excel文件之前,您还必须在Globals中调用setHeaders()getDataPosition()方法。

使用EPPlus生成excel的简单示例:

generateExcel()

**这里,用户是要存储在excel文件中的用户列表,_path是保存excel文件的位置。

链接到教程 https://riptutorial.com/epplus

https://itenium.be/blog/dotnet/create-xlsx-excel-with-epplus-csharp/