如何将工作表中的数据检索到字符串变量中?似乎没有方法。
var workbook = ExcelFile.Load("Workbook.xls");
var worksheet = workbook.Worksheets[0];
如何将工作表中的数据转换为字符串?
请帮助我!
答案 0 :(得分:1)
您是想将整个工作表的数据作为文本,还是仅仅是特定的单元格范围,还是仅仅是特定的单元格? 不过,以下是如何将整个工作表的数据转换为TAB格式的字符串:
var workbook = ExcelFile.Load("Workbook.xls");
workbook.Worksheets.ActiveWorksheet = workbook.Worksheets[0];
var options = new CsvSaveOptions(CsvType.TabDelimited);
options.Encoding = new UTF8Encoding(false);
using (var stream = new MemoryStream())
{
workbook.Save(stream, options);
string worksheetAsText = options.Encoding.GetString(stream.ToArray());
// Do something with "worksheetAsText" ...
}
或者不是写入流,而是可以使用StringWriter,如下所示:
using (var writer = new StringWriter())
{
workbook.Save(writer, options);
string worksheetAsText = writer.ToString();
// Do something with "worksheetAsText" ...
}
更新(对于GemBox.Document,请参阅下面的评论):
有两种方法可以做到这一点,一种是像上面那样做,并将DocumentModel保存为纯文本格式(TxtSaveOptions)。
另一种方法是使用以下内容:
var document = DocumentModel.Load("Document.docx");
string documentAsText = document.Content.ToString();
答案 1 :(得分:0)
您可以使用此代码
TextBox1.Text=worksheet.Cells[6, 0].Value;
答案 2 :(得分:0)
您可以使用“Microsoft.Office.Interop.Excel”
来实现此目的using Excel = Microsoft.Office.Interop.Excel;
var workbookPath = "your workbookpath";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string currentSheet = "Sheet1"; //name of the sheet
Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
var cellValue = (string)(excelWorksheet.Cells[10, 2] as Excel.Range).Value; //cell is casted to string
现在变量cellvalue保持了sting witch在单元格[10,2]。希望这个问题能够解决问题