c# - 无法将数据表写入Excel c#
问题描述
我正在尝试将data table
值保存到 excel 中。我有一个Load Report
按钮,我从中获取数据到网格视图中。
加载报告按钮代码
private void BtnInvHD_Click(object sender, EventArgs e)
{
string dir = @"C:\Output\Log\HavingDuesLog";
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
string location = Path.Combine(dir, "HavingDues_log_"+name+"_" + DateTime.Now.ToString("dd-MM-yy_hh:mm:ss") + ".xls");
string cs = LoginForm.cs;
date = dtPicker.Value.ToString("yyyy-MM-dd");
if (cnn.State == ConnectionState.Closed)
{
cnn.Open();
}
sqlCmd = new SqlCommand("RptIV030", cnn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("@DateFrom", date);
SqlDataAdapter sqlSda = new SqlDataAdapter(sqlCmd);
sqlSda.Fill(dtData);
dGInvHD.DataSource = dtData;
writeExcelFile(location,dtData);
btnExport.Enabled = true;
//return dtData;
}
写入 Excel 函数
public void writeExcelFile(string location, DataTable read)
{
//Create excel app object
Microsoft.Office.Interop.Excel.Application xlSamp = new Microsoft.Office.Interop.Excel.Application();
if (xlSamp == null)
{
MessageBox.Show("Excel is Not Installed");
//Console.WriteLine("Excel is not Insatalled");
//Console.ReadKey();
return;
}
//Create a new excel book and sheet
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlSamp.Workbooks.Add(misValue);
// get the reference of first sheet.
// store its reference to worksheet
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet = xlWorkBook.ActiveSheet;
// changing the name of active sheet
xlWorkSheet.Name = "Having Dues-" + name + "-Till-" + date;
// column headings
for (var i = 0; i < read.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] = read.Columns[i].ColumnName;
}
// rows
for (var i = 0; i < read.Rows.Count; i++)
{
// to do: format datetime values before printing
for (var j = 0; j < read.Columns.Count; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = read.Rows[i][j];
}
}
//Save the opened excel book to custom location
//Dont forget, you have to add to exist location
xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlSamp.Quit();
//release Excel Object
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSamp);
xlSamp = null;
}
catch (Exception ex)
{
xlSamp = null;
MessageBox.Show(ex.ToString());
}
finally
{
GC.Collect();
}
}
当我执行我的代码时,我可以在 gridview 中查看数据,但无法将其写入 excel 文件。
我收到错误xlWorkBook.SaveAs(location, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
错误信息
无法访问该文件。尝试以下方法之一:
Make sure the specified folder exists. Make sure the folder that contains the file is not read-only. Make sure the filename and folder path do not contain any of the following characters: < > ? [ ] : | or * Make sure the filename and folder path do not contain more than 218 characters.
任何帮助将不胜感激。
解决方案
使用类似这样的东西我认为它很有用:
xlSamp.ActiveWorkbook.SaveAs(filepath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlSamp.ActiveWorkbook.Close(true, missing, missing);
xlSamp.Quit();
- 确保文件名和文件夹路径不超过 218 个字符。
当您的位置路径将是长减少路径时,会出现此错误
- 确保指定的文件夹存在。
- 确保包含该文件的文件夹不是只读的。
确保您的位置文件夹必须存在于该位置并授予对该文件夹的读写权限
- 确保文件名和文件夹路径不包含以下任何字符:< > ? [ ] : | 或者 *
给文件夹名称和文件名正确的格式
推荐阅读
- html - 如何将格式化文本包装在响应式表格中?
- java - ')' 预期,错误:不是语句,错误:';' 预期的
- python - 类型提示值是多种类型?
- javascript - 如何在 webpack 中对 HTML 文件的更改触发 livereload 而无需 webpack 处理这些文件?
- python-3.x - 在keras中打印model.output的张量值输出
- regex - 引号内的正则表达式
- java - Vert.x 将 http 重定向到 https
- sql-server - 将此 XML 分解为名称/值对
- c - 为什么将 unsigned char 声明为“Volatile”会使其与“non-volatile” unsigned char 不兼容?
- python - 如何在 Python 中使用 @ 将列向量与行向量相乘?