C#——数据读写

26 篇文章 1 订阅

1、txt 写入

string FilePath = @".\CommandLog";
DateTime dateTime = DateTime.Now;
if (!Directory.Exists(FilePath))
    Directory.CreateDirectory(FilePath);
string FilelName = string.Format(FilePath + "\\{0:D4}{1:D2}{2:D2}{3:D2}.txt", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour);
swBootLoderErrorlog = new StreamWriter(FilelName, true, Encoding.UTF8);
//开始写入
swBootLoderErrorlog.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   " + str+"   "+strID+"   "+Data+"\r\n");
//清空缓冲区
swBootLoderErrorlog.Flush();
//关闭流
swBootLoderErrorlog.Close();



/读取
public void Read(string path)
{
    StreamReader sr = new StreamReader(path,Encoding.Default);
    String line;
    while ((line = sr.ReadLine()) != null) 
    {
         Console.WriteLine(line.ToString());
    }
}

2、CSV 写入

DateTime EndTime = DateTime.Now;
TimeSpan timeSpan = EndTime.Subtract(BeginTime).Duration();
if (timeSpan.Hours >= 3)
{
    FilelName = string.Format(File_Path + "\\{0:D4}{1:D2}{2:D2}{3:D2}.csv", EndTime.Year, EndTime.Month, EndTime.Day, EndTime.Hour);
    BeginTime = EndTime;
}
else
{
    FilelName = string.Format(File_Path + "\\{0:D4}{1:D2}{2:D2}{3:D2}.csv", BeginTime.Year, BeginTime.Month, BeginTime.Day, BeginTime.Hour);
}
if (!Directory.Exists(File_Path))
{
    Directory.CreateDirectory(File_Path);
}
if (!File.Exists(FilelName))
{
    sw = new StreamWriter(FilelName, true, Encoding.UTF8);
    sw.Write("Time,Voltage(V),Current(A),SOC(%),");
    for(int i=0;i<iCellNum;i++)
    {
        sw.Write($"CMU1 Cell[{i}],");
    }
    for (int i = 0; i < iNTCNum; i++)
    {
        sw.Write($"CMU1 Temp[{i}],");
    }
    for (int i = 0; i < iCellNum; i++)
    {
        sw.Write($"CMU2 Cell[{i}],");
    }
    for (int i = 0; i < iNTCNum; i++)
    {
        sw.Write($"CMU2 Temp[{i}],");
    }
    for (int i=0;i<106;i++)
    {
        sw.Write($"{strErrorName[i]},");
    }
    sw.Write("\r\n");
    sw.Flush();
    sw.Close();

3、CSV读取

DateTime BeginTime = DateTime.Now;
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
//创建读这个流的对象,第一个参数是文件流,第二个参数是编码(其实里面的值是多少对我们这个读没有什么问题)
StreamReader sr = new StreamReader(fs, System.Text.Encoding.GetEncoding(936));
string str = "";
int i = 1;
while (str != null)
{
    str = sr.ReadLine();//读取一行
    if (str == null) break;//读完了就跳出循环
    String[] eachLine = new String[4];//因为知道每一行excel有2个单元格,所以string[2]
    eachLine = str.Split(',');//因为.csv文件是以逗号分隔单元格里数据的,所以调用分隔函数split
    htTime.Add(i, eachLine[0]);
    htID.Add(i, eachLine[2]);
    htData.Add(i, eachLine[3]);
    UpdateDataGirdView(i, eachLine);
    i++;
}
for (int j = 1; j <= htID.Count; j++)
{
    bool bAddIntem = true;
    foreach (string v in comCheckBoxList1.Items)
    {
        if (htID[j].ToString() == v)
            bAddIntem = false;
    }
    if (bAddIntem)
        comCheckBoxList1.AddItems(htID[j].ToString());
}
DateTime EndTime = DateTime.Now;
TimeSpan timeSpan = EndTime.Subtract(BeginTime).Duration();
toolStripStatus_Time.Text = "耗时 "+timeSpan.Hours.ToString()+":"+ timeSpan.Minutes.ToString()+":"+ timeSpan.Seconds.ToString();

4、Excel读取(引用 Microsoft.Office.Interop.Excel)

IWorkbook workbook = null;      //
ISheet sheet = null;

FileStream fs = null;           //


try
{
    fs = File.OpenRead(filePath);
}
catch { }
try
{
    //2007版本
    if (filePath.IndexOf(".xlsx") > 0)
        workbook = new XSSFWorkbook(fs);
    // 2003版本  
    else if (filePath.IndexOf(".xls") > 0)
        workbook = new HSSFWorkbook(fs);
    if (workbook != null)
    {
        btnControl(0, 0, 0, 0);
        sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet 
        if (sheet != null)
        {
            rowCount = sheet.LastRowNum;//总行数  
            for (int i = 0; i < rowCount; i++)
            {
                dataGridViewExcel.Rows.Add();
            }
            if (rowCount > 0)
            {
                IRow firstRow = sheet.GetRow(0);//第一行  
                cellCount = firstRow.LastCellNum;//列数  

                //添加列头 
                for (int i = 0; i < cellCount; i++)
                {
                    Header = sheet.GetRow(0).GetCell(i).ToString();
                    listViewProtectionPoint.Columns.Add(Header, 120, System.Windows.Forms.HorizontalAlignment.Left); //第二个是宽度,第三个是对齐方式
                }
                //第一行是列名,则从第二行开始读取 
                labReadStatus.Text = "Read Status: Reading...";
                for (int i = 1; i <= rowCount; i++)
                {
                    if (sheet.GetRow(i).GetCell(0) == null)
                    {
                        break;
                    }
                    if (sheet.GetRow(i).GetCell(0).ToString().Replace(" ", "") != ""
                        && sheet.GetRow(i).GetCell(0).ToString().Replace(" ", "").ToUpper() != "RESERVE"
                        && sheet.GetRow(i).GetCell(0).ToString().Replace(" ", "").ToUpper().Substring(0, 3) != "CHE")
                    {
                        dataGridViewExcel.Rows[i].Cells[0].Value = sheet.GetRow(i).GetCell(0).ToString();
                        AddressFlag = true;
                        if (StartPosisionFlag && sheet.GetRow(i).GetCell(5) != null)      //记录起始位置
                        {
                            PassData.StartPosision = i;
                            StartPosisionFlag = false;      //置为false,记录下一次的起始位置
                        }
                    }

                    if (sheet.GetRow(i).GetCell(0).ToString().Replace(" ", "").ToUpper() == "RESERVE")
                    {
                        //发送指令詢MCU的Flash信息
                        eProtectionPointRead(PassData.ProtectedPointStartAddr, PassData.ProtectedPointReadLen);

                        Thread.Sleep(1000);
                        PassData.ProtectedPointReadLen = 0;
                        PassData.BufferLen = new List<int>();
                        PassData.UnitBuffer = new List<double>();
                        PassData.ASCIIFlag = new List<int>();
                        StartPosisionFlag = true;
                    }
                    Body1 += sheet.GetRow(i).GetCell(0).ToString();
                    ListViewItem item = listViewProtectionPoint.Items.Add(sheet.GetRow(i).GetCell(0).ToString());

                    //添加该行剩余元素
                    for (int j = 1; j < cellCount; j++)
                    {
                        if (sheet.GetRow(i).GetCell(j) == null)
                        {
                            break;
                        }
                        else
                        {
                            Body2 += sheet.GetRow(i).GetCell(j).ToString();
                            if (j == 5)    //十六进制地址列
                            {
                                item.SubItems.Add(sheet.GetRow(i).GetCell(j).StringCellValue);
                                if (AddressFlag)
                                {
                                    PassData.ProtectedPointStartAddr = sheet.GetRow(i).GetCell(j).StringCellValue;
                                    dataGridViewExcel.Rows[i].Cells[j - 1].Value = PassData.ProtectedPointStartAddr;
                                    AddressFlag = false;
                                }
                            }
                            else
                            {
                                item.SubItems.Add(sheet.GetRow(i).GetCell(j).ToString());
                            }
                            if (j == 2)            //name列
                            {
                                dataGridViewExcel.Rows[i].Cells[j - 1].Value = sheet.GetRow(i).GetCell(j).ToString();
                            }
                            if (j == 3 && sheet.GetRow(i).GetCell(j) != null && sheet.GetRow(i).GetCell(j).ToString().Replace(" ", "") != "")        //记录
                            {
                                PassData.ProtectedPointReadLen += Convert.ToInt32(sheet.GetRow(i).GetCell(j).ToString());
                                dataGridViewExcel.Rows[i].Cells[5].Value = sheet.GetRow(i).GetCell(j).ToString();
                                PassData.BufferLen.Add(Convert.ToInt32(sheet.GetRow(i).GetCell(j).ToString()));
                                TotalLen += Convert.ToInt32(sheet.GetRow(i).GetCell(j).ToString());
                            }
                            if (j == 7)//单位列
                            {
                                dataGridViewExcel.Rows[i].Cells[3].Value = sheet.GetRow(i).GetCell(j).ToString();
                            }
                            if (j == 6)    //精度列
                            {
                                if (sheet.GetRow(i).GetCell(j).ToString().Replace(" ", "") != "" && sheet.GetRow(i).GetCell(j) != null)
                                {
                                    PassData.UnitBuffer.Add(Convert.ToDouble(sheet.GetRow(i).GetCell(j).ToString()));
                                    dataGridViewExcel.Rows[i].Cells[6].Value = sheet.GetRow(i).GetCell(j).ToString();
                                }
                            }
                            if (j == 8)    //判断是否是ASCII
                            {
                                if (sheet.GetRow(i).GetCell(j).ToString().Replace(" ", "") != "" && sheet.GetRow(i).GetCell(j) != null)
                                {
                                    PassData.ASCIIFlag.Add(Convert.ToInt32(sheet.GetRow(i).GetCell(j).ToString()));
                                    DataGridViewASCIIFlag.Add(Convert.ToInt32(sheet.GetRow(i).GetCell(j).ToString()));
                                    dataGridViewExcel.Rows[i].Cells[7].Value = sheet.GetRow(i).GetCell(j).ToString();
                                }
                            }
                        }
                    }
                    listViewProtectionPoint.Items[this.listViewProtectionPoint.Items.Count - 1].EnsureVisible();
                }
            }
        }
    }
}
catch(Exception e)
{
    MessageBox.Show(e.ToString(),"Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    if (fs != null)
    {
        fs.Close();
    }
    btnControl(1, 1, 1, 1);
    return;
}


5、保存Excel

string fileName = "";
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "csv";
saveDialog.Filter = "Excel文件|*.csv";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
    MessageBox.Show("Unable to create excel object. Excel may not be installed on your computer","Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook =
            workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet =
            (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
                                                                             //写入标题             
for (int i = 0; i < dataGridViewExcel.ColumnCount; i++)
{ worksheet.Cells[1, i + 1] = dataGridViewExcel.Columns[i].HeaderText; }
//写入数值
for (int r = 0; r < dataGridViewExcel.Rows.Count; r++)
{
    for (int i = 0; i < dataGridViewExcel.ColumnCount; i++)
    {
        worksheet.Cells[r + 2, i + 1] = dataGridViewExcel.Rows[r].Cells[i].Value;
    }
    System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
MessageBox.Show(fileName + "Data saved successfully", "Tips", MessageBoxButtons.OK, MessageBoxIcon.None);
if (saveFileName != "")
{
    try
    {
        workbook.Saved = true;
        workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
    }
    catch (Exception ex)
    {//fileSaved = false;                      
        MessageBox.Show("Error exporting file, the file may be open!\n" + ex.Message,"Error",MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
xlApp.Quit();
GC.Collect();//强行销毁  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值