只有第一个数组项被加载到单元格中,它们都获得相同的值,而不是每个值都被发送到自己的单元格中
我在保存功能中使用了相同的代码,而使用了以下代码:
var iRowCount = xlSaveWorksheet.UsedRange.Rows.Count;
var newRow = iRowCount + 1;
var timeStamp = DateTime.Now;
var rangeStart = string.Concat("A", newRow.ToString());
var rangeEnd = string.Concat("F", newRow.ToString());
string[] stringSaveArray = new string[] { textBox_Name.Text, textBox_Number.Text, textBox_Client.Text, textBox_Site.Text, richTextBox_Description.Text, timeStamp.ToString() };
Excel.Range rng = xlSaveApp.get_Range(rangeStart, rangeEnd);
rng.Value = stringSaveArray;
此选项效果很好,所以我对为什么在这里而不是在其他功能中起作用感到困惑
private void button_CopyTable_Click(object sender, EventArgs e)
{
var fullTempPath = Directory.GetCurrentDirectory() + "\\temp.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlTempWorkbook = xlApp.Workbooks.Open(fullTempPath);
Excel._Worksheet xlTempWorksheet = xlTempWorkbook.Sheets[1];
string[] stringArray = new string[] { textBox_Name.Text, textBox_Number.Text, textBox_Client.Text, textBox_Site.Text, richTextBox_Description.Text };
Excel.Range rng = xlApp.get_Range("B1","B5");
rng.Value = stringArray;
xlTempWorksheet.Range["A1:B5"].Copy();
Marshal.ReleaseComObject(xlTempWorksheet);
//close and release
xlTempWorkbook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
Marshal.ReleaseComObject(xlTempWorkbook);
//quit and release
xlApp.Quit();
Marshal.ReleaseComObject(xlApp);
}
第一个数组项的值将被放入该范围内的每个单元格,而不是每个项都将进入遍历列表的单元格
答案 0 :(得分:1)
多像元范围接受并返回二维矩形数组。例如(未测试):
xlWorksheet.Range["A1:B1"].Value = new[,] { {1, 2} }; // for "horizontal" range
xlWorksheet.Range["A1:A2"].Value = new[,] { {1}, {2} }; // for "vertical" range
xlWorksheet.Range["A1:B2"].Value = new[,] { {1, 2}, {3, 4} };
水平范围可接受单维数组,而垂直范围则不可接受。
如@TimWilliams在评论中所述,Application.Transpose
或Application.WorksheetFunction.Transpose
可用于将一维数组转换为二维“垂直”数组:
xlWorksheet.Range["A1:A2"].Value = xlApp.Transpose(new[] { 1, 2 });
答案 1 :(得分:0)
使用rng.Value = stringArray;
代替使用rng.Value2 = stringArray;
这将起作用。