我目前正在研究一个小项目(对不起,我对编码很新!)而且我遇到了一个奇怪的问题(从我的观点来看)我被困了几个小时。
我想做什么
使用2个不同的Excel,表格将2 DataGridViews
保存到1个Excel文件中。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace project{
public class ExcelWriter
{
public void WriteDataTableToExcel(DataGridView dgv_RawData, DataGridView dgv_ComputedData, string strFilePath, string Filename)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
var workbook = excel.Workbooks.Add(true);
System.Data.DataTable dt1 = (System.Data.DataTable)(dgv_RawData.DataSource);
System.Data.DataTable dt2 = (System.Data.DataTable)(dgv_ComputedData.DataSource);
AddExcelSheet(dt1, workbook);
AddExcelSheet(dt2, workbook);
workbook.SaveAs(@"C:\Users\person\Desktop\test.xlsx");
workbook.Close();
}
private static void AddExcelSheet(System.Data.DataTable dt, Microsoft.Office.Interop.Excel.Workbook wb)
{
Microsoft.Office.Interop.Excel.Sheets sheets = wb.Sheets;
Microsoft.Office.Interop.Excel.Worksheet newSheet = sheets.Add();
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
newSheet.Cells[1, iCol] = c.ColumnName;
}
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
newSheet.Cells[iRow + 1, iCol] = r[c.ColumnName];
}
}
}
}
}
现在我收到以下3个错误:
- 没有重载的Methode for" SaveAs"需要1个参数
- 没有重载的Methode for"关闭"取0参数
- 没有重载的Methode for" Add"需要0个参数"
醇>
可悲的是,我不知道如何解决这个问题。我已经谷歌搜索了很长一段时间..我首先想到一些using...
条款丢失或类型没有指定,但没有真正有效......
我感谢能得到的每一点帮助!
度过愉快的一天
更新 我有一个小工作环节,我将每个文件分开保存为" csv"有什么方法可以将Datagridviews保存到1 csv与不同的数据表?有任何想法吗?
代码:
public void WriteDataTableToExcel(DataGridView dgv_RawData, DataGridView dgv_ComputedData, string strFilePath, string Filename)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "name.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(filename))
{
try
{
File.Delete(filename);
}
catch (IOException ex)
{
MessageBox.Show("d" + ex.Message);
}
}
int columnCount = dgv_ComputedData.ColumnCount;
string columnNames = "";
string[] output = new string[dgv_ComputedData.RowCount + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += dgv_ComputedData.Columns[i].Name.ToString() + ";";
}
output[0] += columnNames;
for (int i = 1; (i - 1) < dgv_ComputedData.RowCount; i++)
{
for (int j = 0; j < columnCount; j++)
{
output[i] += dgv_ComputedData.Rows[i - 1].Cells[j].Value.ToString() + ";";
}
}
System.IO.File.WriteAllLines(sfd.FileName, output, System.Text.Encoding.UTF8);
}