i在我的Excel片列的B列中获得了所有"良好"单元的范围,在" D"列中找到相应的单元格,并创建了这些单元格的范围。我想将所有这些单元格转换为一个字符串,然后将其粘贴到我的记事本文件中,以便每个单元的字符串之间没有空格,并且它们显示在一条线上。
现在,我的代码将每个单元项目读为其自己的实体,并在单独的行上打印它们。我希望能够迭代一个字符串,因此我希望它们都形成一个整个字符串。
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(comboBox2.Text);
Excel.Worksheet xlWorkSheet =
(Excel.Worksheet)excelWorkbook.Sheets[sheetSpaces];
excelApp.Visible = false;
excelApp.ScreenUpdating = false;
excelApp.DisplayAlerts = false;
Excel.Range last = xlWorkSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
int lastUsedRow = last.Row;
string lastCell = "B" + lastUsedRow.ToString();
Excel.Range range = xlWorkSheet.get_Range("B1", lastCell);
foreach (Excel.Range item in range.Cells)
{
string text = (string)item.Text;
if (text == "Good")
{
//get address of all Good items
string textx = (string)item.Address;
//change address of Good items to corresponing address in D column
string textxcorrect = textx.Replace("B", "D");
//get rid of "$" for address
var cellAddress = textxcorrect.Replace("$", "");
//create range for addresses with the new D column addresses
Excel.Range xlRng = xlWorkSheet.get_Range(cellAddress, Type.Missing);
string fileLocation = @"C:\Users\npinto\Desktop\hopethisworks.txt";
foreach (Excel.Range item2 in xlRng)
{
xlRng.Copy();
File.WriteAllText(fileLocation, Clipboard.GetText());
}
string readText = System.IO.File.ReadAllText(fileLocation);
Console.WriteLine(readText);
我已经根据您的原始问题更新了答案 - 如果我现在正确理解了第B中的单元格,将包含"良好"一词 - D列中同一行中的单元格将包含单个单元格引用 - 例如A4&您想附加该数据。
注意 - 如果列列包含" a4" - 那么返回的文本将是您所需的附加内容 - 因此,只需confatenate nextAddress而不是获取xlrng2。
这是怎么回事 - 取决于您可能需要使用stringBuilder而不是字符串的文本大小 - 但是使用少量数据,没有任何显着差异。
string RequiredOutputString = String.Empty;
foreach (Excel.Range item in range.Cells)
{
string text = (string)item.Text;
if (text == "Good")
{
//get address of all Good items
string textx = (string)item.Address;
//change address of Good items to corresponing address in D column
var cellAddress = textx.Replace("$B", "D");
// get a reference to cell in column D
Range xlRng = curWorkSheet.get_Range(cellAddress, Type.Missing);
// get the cell address in row D cell
string nextAddr = xlRng.Text;
// get a reference to the cell point to from Row D
Range xlRng2 = curWorkSheet.get_Range(nextAddr, Type.Missing);
// append that cell contents
RequiredOutputString += xlRng2.Text.Trim();
}
}
string fileLocation = @"C:\Users\npinto\Desktop\hopethisworks.txt";
File.WriteAllText(fileLocation, RequiredOutputString);