简体   繁体   English

(C#-Excel)如何为每个现有行的新列写一个公式?

[英](C# - Excel) How do I write a formula to a newly created column for each existing row?

Say you have an excel file with a bunch of numbers and rows, about 100 rows. 假设您有一个Excel文件,其中包含大量数字和行,大约100行。

I want to programatically write a column with a formula that adds the values of a bunch of fields together for each existing row. 我想以编程方式编写一列,并为每个现有行将一堆字段的值相加。

So first of all, of course, I would create the Openfiledialog for the Excel file, find the path, open it up through OleDb. 因此,首先,我当然要为Excel文件创建Openfile对话框,找到路径,然后通过OleDb打开它。 Got this down. 下来了 Now say I have the following table: 现在说我有下表:

[ Friends | [ 朋友| Money | 钱| Money Lost | 金钱损失 Days passed | 天数| Solution ] 解决方案 ]

Bilbo , 50 , 50 , 7 , *Formula here Bilbo,50,50,7,*公式在这里

Bilso , 80 , 50 , 7 , *Formula here Bilso,80,50,7,*公式在这里

etc... 等等...

Problem is, I don't have an exact number for the rows so I'll have to enumerate whatever is found by the OleDb connection. 问题是,我没有确切的行号,所以我必须枚举OleDb连接找到的任何内容。 The formula would be something like =(B2-C2)*D2 but 2 is also wrong and it would have to be relative to whatever row it's on, ie: row 3 would be =(B3-C3)*D3. 该公式类似于=(B2-C2)* D2,但2也是错误的,它必须相对于它所在的任何行,即:第3行为=(B3-C3)* D3。 I'm not sure how to do this. 我不确定该怎么做。

I found out writing directly to the cell also doesn't make the formula process the numbers outright. 我发现直接写入单元格也不会使公式直接处理数字。

===== =====

EDIT: 编辑:

    private Excel.Application Xls;
    private Excel.Workbooks WBs;
    private Excel.Workbook WB;
    private Excel.Worksheet WS;
    private Excel.Sheets SS;
    Excel.Range cellsRange = null;
    Excel.Range columnRange = null;
    Excel.Range rowRange = null;
    int numberOfColumns = 0;
    int numberOfRows = 0;
    private void btnColumn_Click(object sender, EventArgs e)
    {
        if (btnColumn.FlatStyle == FlatStyle.Flat)
            btnColumn.FlatStyle = FlatStyle.Standard;
        else
        {
            btnColumn.FlatStyle = FlatStyle.Flat;
        }

        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Excel Files|*.xls;*.xlsx";
        openFileDialog.ShowDialog();
        string pather = openFileDialog.FileName;

        if (pather == "" || pather == " " || pather == null)
        {
            return;
        }

        if (!string.IsNullOrEmpty(openFileDialog.FileName))
        {
            try
            {
                Xls = new Excel.Application();
                WBs = Xls.Workbooks;
                WB = WBs.Open(pather, 0, false, 5, "", "", true,
                    XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                SS = WB.Worksheets;
                WS = SS.get_Item(1);                    
                cellsRange = WS.Cells;
                columnRange = cellsRange.Columns;
                rowRange = cellsRange.Rows;
                numberOfColumns = columnRange.Count;
                numberOfRows = rowRange.Count;
                int LastCell = numberOfColumns+1;
                WS.Cells[1, LastCell] = "Tax Formula";
                for (int i = 2; i < numberOfRows; i++)
                {
                    //string niceFormula = "=SUM(L" + i + ",M" + i + ")*N"+ i ;
                    //WS.Cells[i, LastCell].Formula = niceFormula;
                    WS.Cells[i, LastCell].Value = (WS.Cells[i, 12] + WS.Cells[i, 13]) * WS.Cells[i, 14];
                }
                //==========================
                WB.Save();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Write Excel: " + ex.Message);
            }
            finally
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                WB.Close();
                Xls.Quit();

                releaseObject(cellsRange);
                releaseObject(columnRange);
                releaseObject(rowRange);
                releaseObject(SS);
                releaseObject(WS);
                releaseObject(WBs);
                releaseObject(WB);
                releaseObject(Xls);
            }
        MessageBox.Show("Finished Updating File", "Task complete");
    }
}

Anyone know why this code is throwing the following error on write attempt? 有人知道为什么这段代码在写尝试时会引发以下错误吗?

HRESULT: 0x800A03EC 结果:0x800A03EC

Repasted entire code for your convenience. 为了您的方便,拒绝了整个代码。 It's still spitting out the HRESULT error. 它仍然吐出HRESULT错误。

Targeted item is 4 rows deep with 1 row of headers and about 16 columns wide. 目标项目深4行,标题1行,宽16列。

Edit: 编辑:

You may want to try this: 您可能要尝试以下操作:

numberOfColumns = WS.UsedRange.Columns.CountLarge;
numberOfRows = WS.UsedRange.Rows.CountLarge;

Ugh, also change them to long instead of int if you use CountLarge instead of Count CountLarge ,如果您使用CountLarge而不是Count ,也将它们更改为long而不是int

Okay - I got this working finally - no clue why I was having so many issues. 好的-我终于完成了这项工作-不知道为什么我遇到了这么多问题。

For me, I apparently have to make the application visible or it doesn't work. 对我来说,我显然必须使该应用程序可见或不起作用。

There may be another workaround - I pulled it from here: https://stackoverflow.com/a/17061714/1274820 可能还有另一种解决方法-我从这里将其删除: https : //stackoverflow.com/a/17061714/1274820

This code worked for me finally: 这段代码终于对我有用:

Note that this is a console application (figured I would rule that out), but you should just be able to add the magic lines. 请注意,这是一个控制台应用程序(图我将其排除在外),但是您应该只能添加魔术线。

Application excelApp = new Application();
excelApp.SheetsInNewWorkbook = 1;
////////////////////////////////////////////
//Add these lines to make it work???
////////////////////////////////////////////
try {
    excelApp.Visible = true;
}
catch {} 
////////////////////////////////////////////
Workbook excelWB = excelApp.Workbooks.Open(@"C:\test.xls", Type.Missing, false);
_Worksheet excelWS = excelWB.Sheets[1];
Range cellsRange = excelWS.UsedRange;
long LastCell = cellsRange.Columns.CountLarge + 1;
long numberOfRows = cellsRange.Rows.CountLarge;
excelWS.Cells[1, LastCell] = "Tax Formula";
for (int i = 2; i <= numberOfRows; i++)
{
    string niceFormula = "=SUM(L" + i + ",M" + i + ")*N" + i;
    excelWS.Cells[i, LastCell].Formula = niceFormula;
}
excelWB.Close(true);
excelApp.Quit();

Before: 之前:

之前

After: 后:

后

How to fill a DataTable with an excel spreadsheet: 如何用Excel电子表格填充DataTable:

//////////////////////////////////////////////////////////////////////////////////
//This function is absolute magic >.> - Fill DataTable with excel spreadsheet
//HDR=YES means "Spreadsheet has headers" Change to NO if not.
//name = "Log"; - This is the Sheet name to pull the data from
//////////////////////////////////////////////////////////////////////////////////
//oconn takes an SQL like command (Select Everything from name sheet) using con
//HDR=YES means that our data has headers :)
//////////////////////////////////////////////////////////////////////////////////
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + copyToPath + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [Log$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
con.Close();
//////////////////////////////////////////////////////////////////////////////////

Why not use the R1C1 reference style? 为什么不使用R1C1参考样式? That way your formula does not need to be relative to the column. 这样,您的公式就不必相对于列。

For reference: https://excelmate.wordpress.com/2013/04/22/excel-r1c1-reference-style-vs-a1/ 供参考: https : //excelmate.wordpress.com/2013/04/22/excel-r1c1-reference-style-vs-a1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#如何通过Linq查询将列添加到现有数据表中的每个数据行? - C# How do you add a column to an existing datatable for each data row by Linq query? 如何用 c# 编写 excel 公式直到 excel 的最后一行(互操作)? - How to write excel formula with c# until last row of the excel (interop)? 如何在C#中的数据集中的新创建的列中插入数据 - How to insert the data in the newly created column in the dataset in C# 如何在C#中的内联SQL语句的插入语句之后返回新创建的ID? - How do I return the newly created ID after an insert statement from an inline SQL statement in C#? 如何在VSTO / C#中使用行号和列号获取Excel范围? - How do I get an Excel range using row and column numbers in VSTO / C#? C#如何写入数组的每个部分? - C# How do I write to each part of my array? 如何测量C#中每一行的执行时间 - How do I measure execution time for each row in C# 我应该在 C# 中触发哪个事件来编写新创建的 excel 文件? - Which event should I fire in C# for programming a newly created excel file? 如何在 C# 中将数据写入现有 Excel 文档 - How to write data to an existing Excel doc in C# 如何使用 C# 写入现有 Excel (xlsc) 文件中的特定单元格 - How to write to specific cells in an existing Excel (xlsc) file with C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM