为了澄清,我试图将每个Excel整行转移到列表中。在简化示例的情况下,我试图将第一行转换为字符串数组。
我已经完成了几个帖子,主题是转换Excel电子表格的每一行并将每一行转移到一个列表,包括此post
尽管玩弄了一些例子,我仍然遇到转换错误。我将我的程序缩小到一个简单的例子,只是卸载第一行,其中包含列标题到字符串数组中,我收到一个错误,说不能将通用列表转换为字符串[]。
我可以使用Console.Write(String.Format(dataRange.Value2.ToString() + " ")
打印第一行,但无法保存第一行。
以下是产生错误的简化程序:
static void Main(string[] args)
{
string [] m_column_headings;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("H:\\my_documents\\testFile.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
Range dataRange = (Range)wx.Cells[1, 1];
m_column_headings = dataRange.Cast<object>().Select(o => o.ToString()).ToList(); <--- This line gets the error.
根据答案,我做了以下修改以保持类型正确,但我无法看到我指定的内容。
dataRange = (Range)wx.Cells[1, 1];
m_column_headings =
dataRange.Cast<object>().Select(o => o.ToString()).ToArray();
答案 0 :(得分:0)
You are trying to retrieve string Array
but then asking the code to return .ToList()
. Either convert m_column_headings to a list, or change the return type to .ToArray()
i.e.
m_column_headings = dataRange.Cast<object>().Select(o => o.ToString()).ToArray();
答案 1 :(得分:0)
我很感激答案和评论。他们帮我慢慢弄清楚出了什么问题:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace ExcelTest1
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open("H:\\my_documents\\town\\personnel\\May 18 MuniRosterDetailReport.xlsx");
Microsoft.Office.Interop.Excel.Worksheet wx = excel.ActiveSheet as Microsoft.Office.Interop.Excel.Worksheet;
Range dataRange = null;
int totalColumns = wx.UsedRange.Columns.Count;
int totalRows = wx.UsedRange.Rows.Count;
List<string> m_column_headings = new List<string>();
dataRange = (Range)wx.UsedRange;
int row = 1;
for(int colIdx = 1; colIdx < (totalColumns + 1); colIdx++)
{
Range tempRange = (Range )wx.Cells[row, colIdx];
m_column_headings.Add(String.Format(tempRange.Value2.ToString() + ","));
}
int i = 0;
wbv.Close(true, Type.Missing, Type.Missing);
excel.Quit();
}
}
}