我正在使用电子表格齿轮生成制表符分隔的文件,它工作正常,但问题是如果数据表中的任何列具有带有逗号(","字符)的值,那么电子表格会自动用双引号将文本括起来。
如果文本有逗号字符,有没有办法不加双引号?
这是我用来生成制表符分隔文件的代码:
Dim workbook As SpreadsheetGear.IWorkbook
Dim worksheet As SpreadsheetGear.IWorksheet
workbook = SpreadsheetGear.Factory.GetWorkbook()
worksheet = workbook.Worksheets("Sheet1")
Dim cells As SpreadsheetGear.IRange
cells = worksheet.Cells
cells.CopyFromDataTable(dt, Data.SetDataFlags.None)
workbook.SaveAs(strFilePath, SpreadsheetGear.FileFormat.UnicodeText)
worksheet = Nothing
workbook.Close()
workbook = Nothing
您可以循环访问cells
中每个单元格的文本并取出引号。引号可以使用双双引号 (") 放在字符串中(或找到),这看起来很奇怪,但可以完成工作。例如,您可以使用cellText.Replace("",")删除引号。
在 SpreadsheetGear 中没有可用于修改此行为的选项。 SpreadsheetGear 通常在 Excel 之后对其行为进行建模,您会注意到 Excel 在保存到 Unicode Text 时遇到逗号时也会执行相同的操作。
您可能只需要构建自己的"SaveToUnicodeText"例程,该例程根据应用程序的特定要求构造文件。 下面是一些示例代码,它们可能会帮助您开始使用此类例程。 请注意,此代码不能处理传入单元格数据可能遇到的每个可能的"奇怪"情况。 例如,我没有检查涉及换行的病例可能需要如何处理。 此代码只是一个起点,因此您需要考虑根据需要向其添加:
' Create workbook
Dim workbook As SpreadsheetGear.IWorkbook
Dim worksheet As SpreadsheetGear.IWorksheet
workbook = SpreadsheetGear.Factory.GetWorkbook()
worksheet = workbook.Worksheets("Sheet1")
Dim cells As SpreadsheetGear.IRange
cells = worksheet.Cells
' Copy in your data
cells.CopyFromDataTable(dt, Data.SetDataFlags.None)
' Create a couple StringBuilders to help us out.
Dim sb = New StringBuilder()
Dim sbRow = New StringBuilder()
' IWorkbook.SaveAs(...) effectively saves the UsedRange for the worksheet
' for tab-delimited files, so we'll use the same range.
Dim rangeToSave = worksheet.UsedRange
' Iterate through each row of the used range.
For row = 0 To rangeToSave.RowCount
sbRow.Length = 0
' Now iterate through each cell in the row.
For col = 0 To rangeToSave.ColumnCount
' Build up a tab-delimited string consisting of the formatted text
' for each cell in this row.
sbRow.Append(rangeToSave(row, col).Text).Append(vbTab)
Next
' Trim off any dangling tab characters due to empty cells at the end
' of the row and append as a new line to the main StringBuilder.
sb.AppendLine(sbRow.ToString().TrimEnd(vbTab))
Next
' Save file to disk.
Using stream = New StreamWriter(strFilePath)
stream.Write(sb.ToString())
End Using