C#逐行填充excel单元格

时间:2016-06-03 15:17:14

标签: c# excel

嘿我正在尝试创建这个程序,将输入发送到excel文件,并且我坚持如何将输入存储在下一行。

到目前为止,我能够将文本框中的字符串放到标题下的第二行excel中,但我想让用户能够添加多行。

oXL = new Microsoft.Office.Interop.Excel.Application();
            oXL.Visible = true;

            oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
            oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;


            // -- Workstation Information --
            oSheet.Cells[1, 1] = "UserName";
            oSheet.Cells[1, 2] = "Workstation Name";
            oSheet.Cells[1, 3] = "Manufacturer";
            oSheet.Cells[1, 4] = "Model";
            oSheet.Cells[1, 5] = "Serial";
            oSheet.Cells[1, 6] = "CPU";
            oSheet.Cells[1, 7] = "RAM";
            oSheet.Cells[1, 8] = "OS";
            oSheet.Cells[1, 9] = "Version";
            oSheet.Cells[1, 10] = "Microsoft Office";
            oSheet.Cells[1, 11] = "Recommendations";
            oSheet.Cells[1, 12] = "Comments";

            oSheet.get_Range("A1", "L1").Font.Bold = true;
            oSheet.get_Range("A1", "L1").VerticalAlignment =
                Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

            string[,] saNames = new string[500, 500];

            saNames[0, 0] = txtUsername1.Text;
            saNames[0, 1] = txtWorkName1.Text;
            saNames[0, 2] = cbxManufac.Text;
            saNames[0, 3] = cbxMachType.Text;
            saNames[0, 4] = txtModel.Text;
            saNames[0, 5] = txtSerial.Text;
            saNames[0, 6] = txtCPU.Text;
            saNames[0, 7] = cbxRAM.Text;
            saNames[0, 8] = cbxOS.Text;
            saNames[0, 9] = txtVersion.Text;
            saNames[0, 10] = txtMcstOffice.Text;
            saNames[0, 11] = txtRecomend.Text;
            saNames[0, 12] = txtComments.Text;


            oSheet.get_Range("A2", "L1000").Value2 = saNames;

            oWB.SaveAs("discoSurvey");

这就是我的保存按钮目前的样子。我想创建一个添加按钮,让他们继续向此Excel工作表添加信息。如何将它们移动到下一行?

1 个答案:

答案 0 :(得分:0)

嗯,

你需要找到Excel文件中的第一个空行来添加下一行,对吗?

因此您可以使用建议的for循环搜索下一个空行,然后使用找到的rowindex插入您的值。

我只是更清楚地看到了这一点......

        string[,] saNames = new string[500, 500];

        saNames[0, 0] = txtUsername1.Text;
        saNames[0, 1] = txtWorkName1.Text;
        saNames[0, 2] = cbxManufac.Text;
        saNames[0, 3] = cbxMachType.Text;
        saNames[0, 4] = txtModel.Text;
        saNames[0, 5] = txtSerial.Text;
        saNames[0, 6] = txtCPU.Text;
        saNames[0, 7] = cbxRAM.Text;
        saNames[0, 8] = cbxOS.Text;
        saNames[0, 9] = txtVersion.Text;
        saNames[0, 10] = txtMcstOffice.Text;
        saNames[0, 11] = txtRecomend.Text;
        saNames[0, 12] = txtComments.Text;

虽然我不喜欢500x500数组 - 你所要做的就是连续查询你的数组中的null并使用该索引插入值。 但你需要保持你的阵列不要一直重新定义它...把它放到一个字段上。