C# 将list数组保存成xls表格

 
  
            List listName=new List();
            listName.Add("时间");
            listName.Add("标签ID");
            listName.Add("X轴");
            listName.Add("Y轴");
            listName.Add("Z轴");
            listName.Add("温度");
            listName.Add("湿度");
            listName.Add("电量");
            //将listView1中的数据保存到excel表格中
            object misValue = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
            Worksheet xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.get_Item(1);
            for (int i = 0; i < listName.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1] = listName[i]; //write the column name
            }
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                listView1.Items[i].Selected = true;//触发选中第一行 
                xlWorkSheet.Cells[i + 2, 1] = listView1.SelectedItems[0].SubItems[0].Text.ToString();//第i行第一列
                xlWorkSheet.Cells[i + 2, 2] = listView1.SelectedItems[0].SubItems[1].Text.ToString();//第i行第二列
                xlWorkSheet.Cells[i + 2, 3] = listView1.SelectedItems[0].SubItems[2].Text.ToString();
                xlWorkSheet.Cells[i + 2, 4] = listView1.SelectedItems[0].SubItems[3].Text.ToString();
                xlWorkSheet.Cells[i + 2, 5] = listView1.SelectedItems[0].SubItems[4].Text.ToString();
                xlWorkSheet.Cells[i + 2, 6] = listView1.SelectedItems[0].SubItems[5].Text.ToString();
                xlWorkSheet.Cells[i + 2, 7] = listView1.SelectedItems[0].SubItems[6].Text.ToString();
                xlWorkSheet.Cells[i + 2, 8] = listView1.SelectedItems[0].SubItems[7].Text.ToString();
		......
            }
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.InitialDirectory = Directory.GetCurrentDirectory() + "\\data\\";
                sfd.Filter = "Excel表格|*.xls";
                sfd.ShowDialog();
                string path = sfd.FileName;
                xlWorkBook.SaveAs(path, XlFileFormat.xlExcel7, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
                MessageBox.Show("保存成功!");
            }
            catch (Exception)
            { }


 
  
 
  
 
  
 
  
 
 

你可能感兴趣的:(C# 将list数组保存成xls表格)