我正在使用spreadsheetgear生成制表符分隔文件,它工作正常,但问题是如果datatable中的任何列都带有逗号(","字符)的值,那么spreadsheetgear会自动用双引号括住文本
如果文字有逗号字符,是否可以不加双引号?
以下是我用来生成制表符分隔文件的代码:
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
答案 0 :(得分:0)
您可以遍历cells
中每个单元格的文本并取出引号。可以使用双引号("")将引号放在(或找到)字符串中,这看起来很奇怪,但可以完成工作。例如,您可以使用cellText.Replace("""","")来删除引号。
答案 1 :(得分:0)
在SpreadsheetGear中没有可用于修改此行为的选项。 SpreadsheetGear通常会在Excel之后模拟其行为,并且您会注意到Excel在保存到Unicode文本时遇到逗号时会执行相同的操作。
您可能只需要构建自己的" 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