繁体   English   中英

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

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

假设您有一个Excel文件,其中包含大量数字和行,大约100行。

我想以编程方式编写一列,并为每个现有行将一堆字段的值相加。

因此,首先,我当然要为Excel文件创建Openfile对话框,找到路径,然后通过OleDb打开它。 下来了 现在说我有下表:

[ 朋友| 钱| 金钱损失 天数| 解决方案 ]

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

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

等等...

问题是,我没有确切的行号,所以我必须枚举OleDb连接找到的任何内容。 该公式类似于=(B2-C2)* D2,但2也是错误的,它必须相对于它所在的任何行,即:第3行为=(B3-C3)* D3。 我不确定该怎么做。

我发现直接写入单元格也不会使公式直接处理数字。

=====

编辑:

    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");
    }
}

有人知道为什么这段代码在写尝试时会引发以下错误吗?

结果:0x800A03EC

为了您的方便,拒绝了整个代码。 它仍然吐出HRESULT错误。

目标项目深4行,标题1行,宽16列。

编辑:

您可能要尝试以下操作:

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

CountLarge ,如果您使用CountLarge而不是Count ,也将它们更改为long而不是int

好的-我终于完成了这项工作-不知道为什么我遇到了这么多问题。

对我来说,我显然必须使该应用程序可见或不起作用。

可能还有另一种解决方法-我从这里将其删除: https : //stackoverflow.com/a/17061714/1274820

这段代码终于对我有用:

请注意,这是一个控制台应用程序(图我将其排除在外),但是您应该只能添加魔术线。

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();

之前:

之前

后:

后

如何用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();
//////////////////////////////////////////////////////////////////////////////////

为什么不使用R1C1参考样式? 这样,您的公式就不必相对于列。

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM