[英]saving data in csv file
我在將數據保存在 .csv 文件中時遇到問題。
void WriteLog(DataRow rzad)
{
StreamWriter sw = new StreamWriter("log.csv", true);
int iColCount = 8;
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(rzad[i]))
{
sw.Write(rzad[i].ToString());
sw.Write("\t");
}
}
sw.Write("\n");
sw.Flush();
sw.Close();
}
問題是在文件中我在 A 列中有數據。 我想將 DataRow 格式的一行粉碎為 8 個部分,這些部分放在 8 個不同的列中。 我的函數工作,因為它沒有看到選項卡(“\\t”)。
我無法發布圖像,所以我嘗試在 csv 文件中描述結果:
2011-03-17 14:34:11asdPrzekroczono krytyczną minimalną wymaganą wartość parametru5010050080550
這是我的示例行,我想將其粉碎為 8 列:
2011-03-17 14:34:11 asd Przekroczono krytyczną minimalną wymaganą wartość parametru 50 100 500 80 550
"#\\t#" 沒有幫助。 結果是:
"2011-03-17 18:29:17# #asd# #Przekroczono krytyczną, maksymalną, wymaganą wartość parametru# #560# #100# #500# #80# #550# #"
有一些表格,但我的觀點是沒有空格而是過渡到下一個單元格:(
"\" 也無濟於事。
首先,您說您正在寫入 CSV(逗號分隔值)文件。 但是,您實際上是在寫入制表符分隔的文件。 並且,您需要在行之間寫入 /r/n :
這有效:
StreamWriter sw = new StreamWriter(@"c:\log.csv", true);
int iColCount = 8;
for (int i = 0; i < iColCount; i++)
{
{
sw.Write(i.ToString());
sw.Write("\t");
}
}
sw.Write("\r\n");
sw.Flush();
sw.Close();
private ActionResult ExportMeasuresWithTabsFromClient(DataSet spendData,
string excelFileName,
bool isFirstColumnDateAndRestDouble = false
//int numberFormatStartingColumnNumber = -1,
//int dateFieldColumn = -1)
{
var fileName = "Bulk Export" + Guid.NewGuid() + ".xlsx";
// Checking whether the directly exist and save the file to server temp folder
bool exists = System.IO.Directory.Exists(Server.MapPath("~/" + Resource.ExportLocationTemp));// Common temp location for export as it is not saving the file in the location
if (!exists)
{
DirectoryInfo di = System.IO.Directory.CreateDirectory(Server.MapPath("~/" + Resource.ExportLocationTemp));
if (di == null || !di.Exists)
{
var msg = $"{Resource.MP_CreateDirectory_Failed} '{Resource.ExportLocationTemp}'.";
_log.Error(msg);
throw new Exception(msg);
}
}
var fullPath = Path.Combine(Server.MapPath("~/" + Resource.ExportLocationTemp), fileName);
_log.Info("Entering ExportMeasuresWithTabsFromClient");
//Write the workbook to a memory stream
MemoryStream output = new MemoryStream();
try
{
XSSFWorkbook workbook = new XSSFWorkbook();
foreach (DataTable dt in spendData.Tables)
{
if (getOneWorksheet(workbook, dt)) //, isFirstColumnDateAndRestDouble, numberFormatStartingColumnNumber, dateFieldColumn))
_log.Info($"Created worksheet for TableName: '{dt.TableName}'");
else
_log.Error($"Failed to create worksheet for TableName: '{dt.TableName}'");
}
using (FileStream file = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
{
workbook.Write(file);
}
//Return the result to the end user
//TempData.Add("downloadStatus", 1);
_log.Info("Exiting ExportMeasuresWithTabsFromClient");
}
catch (Exception ex)
{
_log.Error(ex.Message, ex);
_log.Info("Error in ExportMeasuresWithTabsFromClient");
}
return Json(fileName);
//Suggested file name in the "Save as" dialog which will be displayed to the end user
}
private bool getOneWorksheet(XSSFWorkbook workbook,
DataTable dataTable,
bool isFirstColumnDateAndRestDouble = false)
{
_log.Info("Entering getOneWorksheet");
try
{
//Create new Excel sheet
//var sheet = workbook.CreateSheet(getSheetName(dataTable));
var sheet = workbook.CreateSheet(dataTable.TableName);
//Create a header row
var headerRow = sheet.CreateRow(0);
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
// Setting for the styles for edited cells
ICellStyle styleEditableCells = workbook.CreateCellStyle();
styleEditableCells.IsLocked = false;
styleEditableCells.WrapText = true;
// Setting for the styles for non edited cells
ICellStyle styleForNonEditableCells = workbook.CreateCellStyle();
styleForNonEditableCells.IsLocked = true;
styleForNonEditableCells.FillPattern = FillPattern.AltBars;
styleForNonEditableCells.FillBackgroundColor = NPOI.SS.UserModel.IndexedColors.Grey25Percent.Index;
styleForNonEditableCells.WrapText = true;
int rowNumber = 1;
//Populate the sheet with values from the grid data.
foreach (DataRow dataRow in dataTable.Rows)
{
//Create a new row in Excel sheet.
var excelRow = sheet.CreateRow(rowNumber++);
for (int column = 0; column < dataTable.Columns.Count; column++)
{
ICell cell = excelRow.CreateCell(column);
if (isFirstColumnDateAndRestDouble) // if this true --> ROI -> SaveAndDownload button (only for that)
{
// Protecting the sheet and setting the styles (editing and non editing)
sheet.ProtectSheet(Resource.Modeling_Roi_SaveDonwloadexcelPassword);
if (column == 0 || column == 1)
cell.CellStyle = styleForNonEditableCells;
else
cell.CellStyle = styleEditableCells;
}
//Set values for the cells
double value;
if (double.TryParse(dataRow[column].ToString(), out value))
cell.SetCellValue(value);
else
cell.SetCellValue(dataRow[column].ToString());
}
}
for (int column = 0; column < dataTable.Columns.Count; column++) // Looping and wraping the column values
{
headerRow.CreateCell(column).SetCellValue(dataTable.Columns[column].ColumnName);
sheet.AutoSizeColumn(column);
if (sheet.GetColumnWidth(column) / 255 < 254) /// DDE 1.5 6170 --> Handling the higher exponential value
{
sheet.SetColumnWidth(column, sheet.GetColumnWidth(column) + (2 * 256));
}
}
return true;
}
catch (Exception ex)
{
_log.Error(ex.Message, ex);
_log.Info("Error in getOneWorksheet");
}
return false;
}
以防萬一您一年前寫了這個問題后仍然沒有找到解決方案:
您可以使用非常流行的 KBCSV 庫,它幾乎可以處理您需要的所有內容。 它默認使用 csv,但可以輕松修改以處理 tsv。
對於一個非常簡單且容易破解的解決方案,您可以嘗試: string.Join("\\t", rzad) + "\\r\\n"
這不會考慮包含選項卡的字段。 如果一個字段包含一個選項卡,它將使此方法無用。 通常包含分隔符的字段是雙引號的,包含雙引號的字段是雙雙引號的。
實現這一點並不難,但它會重新發明輪子,因為 Kent Boogart 已經花了很多時間考慮一些我不知道的邊緣情況。
以下函數用於寫入csv文件。
public static void WriteCSV(string file, string content)
{
using (StreamWriter sw = new StreamWriter(file))
{
sw.Write(content);
}
}
然后通過調用這個函數
string appendText = "";
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(rzad[i]))
{
appendText += appendText == "" ? rzad[i].toString() : "," + rzad[i].toString();
}
}
WriteCSV("C:\\out\\out.csv",appendText);
多行的另一個簡單示例,每行由換行符 '\\n' 分隔。
WriteCSV("C:\\out\\out.csv","a,b,c,d,e,f,g\nh,i,j,k,l,m,n\n");
我傾向於同意@Hossein。 我認為這是一個編碼問題。 我在我的機器上運行了你的代碼,它運行得很好。
if (editLabelsDT != null)
{
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet();
sheet.ProtectSheet(Resource.Input_ExportEditMeasureLabel);
ICellStyle styleEditableCells = workbook.CreateCellStyle();
styleEditableCells.IsLocked = false;
styleEditableCells.WrapText = true;
ICellStyle styleForNonEditableCells = workbook.CreateCellStyle();
styleForNonEditableCells.IsLocked = true;
styleForNonEditableCells.FillPattern = FillPattern.AltBars;
styleForNonEditableCells.FillBackgroundColor = NPOI.SS.UserModel.IndexedColors.Grey25Percent.Index;
styleForNonEditableCells.WrapText = true;
//Create a header row
var headerRow = sheet.CreateRow(0);
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
//Populate the sheet with values from the grid data
foreach (DataRow dr in editLabelsDT.Rows)
{
//Create a new row
var row = sheet.CreateRow(rowNumber++);
for (int i = 0; i < editLabelsDT.Columns.Count; i++)
{
ICell cell1 = row.CreateCell(i);
if (i == 0)
cell1.CellStyle = styleForNonEditableCells;
else
cell1.CellStyle = styleEditableCells;
//Set values for the cells
cell1.SetCellValue(dr[i].ToString());
}
}
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Customers");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.