我正在尝试将excel转换为dataset
进行某些处理。我使用以下代码:
private DataSet ConvertExcelToDataset(string path, string sheetName)
{
Excel.Application oExcel = null;
Excel.Workbooks workbooks = null;
Excel.Workbook workbook = null;
Excel.Range range = null;
try
{
oExcel = new Excel.Application();
workbooks = oExcel.Workbooks;
workbook = workbooks.Open(path);
DataSet ds = new DataSet();
foreach (Excel.Worksheet sheet in workbook.Worksheets)
{
//If passed sheetName is "All" then reading all sheets
//If passed sheetName is not "All" then reading only sheet whose name is passed
if (sheetName != "All" && sheet.Name != sheetName)
{
continue;
}
range = sheet.UsedRange;
int rows = range.Rows.Count;
int cols = range.Columns.Count;
DataTable dt = new DataTable(sheet.Name);
int noofrow = 1;
//If 1st Row Contains unique Headers for datatable include this part else remove it
for (int c = 1; c <= cols; c++)
{
string colname = sheet.Cells[1, c].Text;
dt.Columns.Add(colname);
noofrow = 2;
}
for (int r = noofrow; r <= rows; r++)
{
DataRow dr = dt.NewRow();
for (int c = 1; c <= cols; c++)
{
dr[c - 1] = sheet.Cells[r, c].Text;
}
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
//clean up
Marshal.ReleaseComObject(sheet);
}
//Closing workbook
workbook.Close();
//Closing excel application
oExcel.Quit();
return ds;
}
catch (Exception ex)
{
_logger.Error(ex);
return null;
}
finally
{
//clean up
if (range != null) Marshal.ReleaseComObject(range);
if (workbook != null) Marshal.ReleaseComObject(workbook);
if (workbooks != null) Marshal.ReleaseComObject(workbooks);
if (oExcel != null) Marshal.ReleaseComObject(oExcel);
}
}
它工作正常但是如果假设excel文件中的行中的任何单元格包含包含超过30,000个字符的大字符串,则会被截断。经过调试后,我发现了以下行中的问题
dr[c - 1] = sheet.Cells[r, c].Text;
那么我怎样才能避免这种字符串截断?