請問,有沒有什麼辦法可以合計(總結)給定列的單元格(行)的內容,其中可能的行數單元格)是動態的,也就是說,行數不固定,在Excel工作表中?我一直在嘗試沒有任何有意義的結果,我嘗試使用偏移量,但繼續從HRESULT等等一些COM_Exception等等......計算WPF中excel列的動態單元格/行的總和
下面是試圖用於實現我的目的的演示代碼的一部分。
請高度讚賞任何建議(與代碼片段)。
private void button1_Click(object sender, RoutedEventArgs e)
{
excel.Application xlApp;
excel.Workbook xlWorkBook;
excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new excel.Application();
var MyExcel = new excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
excel.Range chartRange;
chartRange = xlWorkSheet.get_Range("$A:$A", Type.Missing);
xlWorkSheet.Cells[1, 1] = "Temperature(deg)";
xlWorkSheet.Cells[1, 2] = "Humidity(m-3)";
xlWorkSheet.Cells[1, 3] = "Wind Speed(m/s)";
xlWorkSheet.Cells[2, 1] = 33;
xlWorkSheet.Cells[2, 2] = 45;
xlWorkSheet.Cells[2, 3] = 34;
xlWorkSheet.Cells[3, 1] = 23;
xlWorkSheet.Cells[3, 2] = 26;
xlWorkSheet.Cells[3, 3] = 43;
xlWorkSheet.Cells[4, 1] = 45;
xlWorkSheet.Cells[4, 2] = 24;
xlWorkSheet.Cells[4, 3] = 34;
xlWorkSheet.Cells[5, 1] = 40;
xlWorkSheet.Cells[5, 2] = 32;
xlWorkSheet.Cells[5, 3] = 42;
decimal fdt = 0;
int i = 2;
excel.Range targetRange = (excel.Range)xlWorkSheet.Cells[2, 1];
while (xlWorkSheet.Cells.Offset[i, 0].Value2 != null)
{
i++;
fdt += xlWorkSheet.Cells.Offset[i, 0].Value2;
}
MessageBox.Show(fdt.ToString());
excel.ChartObjects xlCharts = (excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
excel.ChartObject myChart = (excel.ChartObject)xlCharts.Add(400, 50, 400, 300);
excel.Chart chartPage = myChart.Chart;
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = excel.XlChartType.xl3DColumnClustered;
try
{
myChart.Chart.HasTitle = true;
excel.Range objRange = (excel.Range)xlWorkSheet.Cells["$A:$A", Type.Missing];
String strData = objRange.get_Value(misValue).ToString();
myChart.Chart.ChartTitle.Text = strData;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
xlWorkBook.SaveAs("DemoChart_1.xls", excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlApp.Visible = true;
}
感謝您的回覆,但使用您的建議爲:while(xlWorkSheet.Cells [i,1]!= null)//其中i = 2且在while循環內{i ++; targetRange.Value2 + = xlWorkSheet.Cells [i,1] .Value2; }這次給了我一個空輸出......我想我需要增加一點努力使它按照我想要的方式工作,但實際上並不知道該怎麼做。我真的卡住了。 – 2012-04-30 10:22:12
你試圖總結什麼專欄? 'Cells [i,1]'是第一列(「A」)。此外,你可以嘗試不使用'.Value2',但我今天晚些時候將在WPF中嘗試它。祝你好運! – Zairja 2012-04-30 12:45:26
是的,這是第一個嘗試Sum的列。我是讓我迭代或循環通過A列的行。好的,我會耐心等待您的反饋。 – 2012-04-30 13:56:15