如何将Excel范围复制到文本(.txt)文件,无格式,以便所有单元格形成一个单一的string,不是单独的项目? C#

我在Excel工作表的B列中find了一系列“Good”单元格,在“D”列中find相应的单元格,并创build这些单元格的范围。 我想将所有这些单元格转换为一个单一的string,并将其粘贴到我的记事本文件,以便每个单元格的string之间没有空格,它们显示在一行上。

现在我的代码读取每个单元格项目作为自己的实体,并打印在不同的行。 我想能够遍历一个单一的string,所以我想他们都形成一个完整的string。

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&追加这些数据。

注意 – 如果列D单元格包含“+ A4” – 那么返回的文本将是你需要附加的 – 所以只需连接nextAddress而不是得到xlRng2。

怎么样 – 根据文本的大小,你可能想使用一个StringBuilder而不是string – 但与less量的数据不会有任何显着的差异。

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